Я пытаюсь создать простой класс дат. Мой профессор также хочет, чтобы мы включили наш собственный метод .equals в класс дат, который должен сравнивать два объекта. Моя проблема в том, что мой метод возвращает false, если я не сравниваю один и тот же объект, даже если их значения совпадают.
Вот мой драйвер:
public class Lab3Driver {
public static void main(String[] args) {
Date theDate = new Date(6, 30, 1995);
Date anotherDate = new Date(6, 30, 1995);
System.out.println(theDate.equals(anotherDate));
System.out.println(theDate);
System.out.println(anotherDate);
}
}
Вот мой класс даты:
public class Date {
private int month;
private int day;
private int year;
public Date() // default no arg constructor
{
this.month = 1; // set to date I completed this class, for fun.
this.day = 26;
this.year = 2019;
}
public Date(int m, int d, int y) // normal constructor in case you want to initialize variables upon object declaration
{
this.month = m;
this.day = d;
this.year = y;
}
public int getMonth() {
return month;
}
public void setMonth(int month)
{
if (month >= 1 && month <= 12) // if else that checks and makes sure months are between 1 and 12
{
this.month = month;
}
else
{
System.out.println("Invalid month input. Months are between 1 and 12.");
}
}
public int getDay()
{
return day;
}
public void setDay(int day)
{
if (day >= 1 && day <= 31) // if else that checks and makes sure days are between 1 and 31
{
this.day = day;
}
else
{
System.out.println("Invalid day input. Days are between 1 and 31.");
}
}
public int getYear()
{
return year;
}
public void setYear(int year) // year can be set to anything, in the case that this program is used for something
{ // other than the present day, as in a reference to the past or future
this.year = year;
}
public String toString() // to string in order to print out the date that is stored
{
String theDate = "The date is: " + this.month + "/" + this.day + "/" + this.year;
return theDate;
}
public boolean equals(Object that) // compares two objects and checks for null/type casting
{
if (this == that)
return true;
else if(that == null || that.getClass()!= this.getClass())
{
System.out.println("Null or type casting of argument.");
return false;
}
else
return false;
}
Что-то с этим методом создает проблему, я думаю:
public boolean equals(Object that) // compares two objects and checks for null/type casting
{
if (this == that)
return true;
else if(that == null || that.getClass()!= this.getClass())
{
System.out.println("Null or type casting of argument.");
return false;
}
else
return false;
}