如何为 java 中的日期创建属性 getter 和 setter?

How to create an attribute, getter, and setter for date in java?

您如何创建 class 的日期属性?我希望将开始日期设置为一个属性,但我在语法上苦苦挣扎

public class Adventure{
     private String Location;
     private int cost;
     private Localdate startDate;

     public void Setdate(int year, int month, int day){
        LocalDate startDate = LocalDate.of(year, month, day);
     }
     public LocalDate getDate(){
        return startDate;
     }
}

出于某种原因,这对我不起作用。前两个私有属性可以忽略,但我只是想为日期属性

做一个getter和setter

您的代码不起作用的原因是因为在 SetDate 方法中您正在设置 值到新变量而不是 class 变量。

class变量-

//accessible to all (non-static)method in class
private Localdate startDate; 

方法变量-

 //only available inside the SetDate method
 LocalDate startDate = LocalDate.of(year, month, day);

总之,两者不同

你可以做这样的事情让它工作

 public void Setdate(int year, int month, int day){
    this.startDate = LocalDate.of(year, month, day);
 }