如何检查java类中的构造函数值?

如何检查java类中的构造函数值?,java,Java,我有一个MyDate类,在这个类中,我需要检查年份(y)是否是闰年。我的代码如下: public class MyDate { private int d; private int m; private int y; //constructor public MyDate(int d, int m, int y) { this.d = d; this.m = m; this.y = y; } public void s

我有一个MyDate类,在这个类中,我需要检查年份(y)是否是闰年。我的代码如下:

public class MyDate
{
    private int d;
    private int m;
    private int y;

//constructor

public MyDate(int d, int m, int y)
    {
    this.d = d;
    this.m = m;
    this.y = y;
    }

    public void setDay(int d)
    {
        this.d = d;
    }

    public int getDay()
    {
        return d;
    }

    public void setMonth(int m)
    {
        this.m = m;
    }

    public int getMonth()
    {
        return m;
    }

    public void setYear(int y)
    {
        this.y = y;
    }   

    public int getYear()
    {
        return y;
    }



    public void setDate(int d, int m, int y)
    {
        setDay(d);
        setMonth(m);
        setYear(y);
    }
这里是否需要使用getYear()而不是(int y)

//像这样

public static boolean isLeap(getYear()) {
  if (y % 4 != 0) {
    return false;
  } else if (y % 400 == 0) {
    return true;
  } else if (y % 100 == 0) {
    return false;
  } else {
    return true;
  }
}

您的方法是静态的,因此如果该方法必须是
static

public static boolean isLeap(int y) 
因为不能在静态方法中调用getYear(),它不属于对象,而是属于类。 如果可以将方法更改为非静态

使用


第二个版本未通过编译:

publicstaticbooleanisleap(getYear()){

首先,您不能在其他方法的声明中调用方法。其次,您不能从静态方法调用实例方法

您可以按以下方式更改方法签名:

public boolean isLeap() {
    // here you can access either instance field y or method getYear()
}

不要为此编写自己的类。
java.util.GregorianCalendar
完成了类所能做的一切,它有一个名为
isLeapYear()

int y
的方法是
isLeap
方法的参数。您可能想使用
getYear()
调用
isLeap
方法时。@Luiggi Mendoza将其作为answer@MrD我不确定这是否能回答OP的问题。如果你觉得可以,你可以将我的评论作为你答案的一部分。@Luiggi Mendoaz,我对java真的很陌生。我必须在这个类中执行一系列函数来检查publi静态bole中d、m、y的值一个,我应该只放(int y)还是(getYear())?我不知道这是怎么工作的?请注意,
isLeap
方法被标记为
static
。OP可能不想更改它。
public boolean isLeap(){
int y = this.getYear();
....
...
} 
public boolean isLeap() {
    // here you can access either instance field y or method getYear()
}