leap year in java : Create a class to find out whether the given year is leap year or not. (Use inheritance for this program)

A leap year is a year that has 366 days instead of the usual 365 days. Leap years occur every four years, except for years that are divisible by 100 but not by 400. For example, the years 2020, 2024, and 2028 are all leap years, but the years 1700, 1800, and 1900 are not leap years.

In this blog post, we will create a class to find out whether the given year is a leap year or not. We will use inheritance to create a subclass for leap years.

Here is a Java Program to find out whether the given year is leap year or not.


class Year {
    private int year;
    public Year(int year) {
    this.year = year;
}

public boolean isLeapYear() {
    if (year % 4 == 0) {
        if (year % 100 == 0) {
        return year % 400 == 0;
    } else {
        return true;
        }
     } else {
            return false;
        }
    }
}

class LeapYear extends Year {
    public LeapYear(int year) {
    super(year);
}

@Override
public boolean isLeapYear() {
    return true;
    }
}

public class Main {
    public static void main(String[] args) {
        Year year = new Year(2020);
        System.out.println(year.isLeapYear()); // true

        LeapYear leapYear = new LeapYear(2024);
        System.out.println(leapYear.isLeapYear()); // true

        Year notLeapYear = new Year(1700);
        System.out.println(notLeapYear.isLeapYear()); // false
    }
}




Explanation


The Year class has a single property, year. The isLeapYear() method checks whether the year is a leap year. If the year is divisible by 4, but not by 100, then it is a leap year. If the year is divisible by 400, then it is also a leap year.

The LeapYear class extends the Year class. The LeapYear class overrides the isLeapYear() method to always return true. This means that any object of the LeapYear class will always be a leap year.

In the main() method, we create objects of the Year and LeapYear classes. We then call the isLeapYear() method on each object to see whether it is a leap year.

As you can see from the output, the Year object that represents the year 2020 is a leap year, the LeapYear object that represents the year 2024 is a leap year, and the Year object that represents the year 1700 is not a leap year.

Comments