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 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/

相关文章:

java - Spring 数据 JPA : Delete Optimistic Locking semantics

java - 处理开启虚拟串口

java - 如何正确使用 JTI 声明和 JWT 来防止重放攻击?

java - Mandrill API Java 单元测试

Java SimpleDateFormat 不会使用 setLenient(false) 解析 2013 年的特定时间

java - JNI 返回随机整数

java - SLF4J - 回退 : How to configure loggers in runtime?

java - PDF 表单填写时出现 iText 错误

java - 在派生类中省略 throws 声明

JavaFX TabPane 标题 OverrunStyle