我有一个 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(int y) {
if (y % 4 != 0) {
return false;
} else if (y % 400 == 0) {
return true;
} else if (y % 100 == 0) {
return false;
} else {
return true;
}
}
//像这样吗?
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;
}
}
最佳答案
您的方法是静态的,因此如果该方法必须是静态
,则应使用以下内容
public static boolean isLeap(int y)
因为你不能在静态方法中调用getYear()。它不属于一个对象,它属于一个类。 是否可以将方法更改为非静态
使用
public boolean isLeap(){
int y = this.getYear();
....
...
}
关于java - 如何检查java类中的构造函数值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16754016/