user1471980
user1471980

Reputation: 10626

how you check the constructor values in java class?

I have a MyDate class, within this class, I need to check if the year (y) is leap year. My code is as follows:

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);
    }

here instead of (int y), do I need to use getYear()?

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;
  }
}

//like this?

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;
  }
}

Upvotes: 0

Views: 118

Answers (3)

Tap
Tap

Reputation: 6522

Don't write your own class for this. java.util.GregorianCalendar does everything your class can do, and it has a method called isLeapYear().

Upvotes: 0

AlexR
AlexR

Reputation: 115328

The second version does not pass compilation:

public static boolean isLeap(getYear()) {

Take a look on this. First, you cannot call method inside declaration of other method. Second, you cannot call instance method from static method.

You can change the method signature as following:

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

Upvotes: 0

Salih Erikci
Salih Erikci

Reputation: 5087

Your method is static, so you should use the following if the method must be static

public static boolean isLeap(int y) 

because you can not call getYear() in a static method.It does not belong to an object, it belongs to a class. If it is possible to change the method as non-static

use

public boolean isLeap(){
int y = this.getYear();
....
...
} 

Upvotes: 1

Related Questions