I have an array of people. I have instantiated the subclass Employee
twice and one Student
subclass in the array. I just want to know why I'm getting false when it should say true with regards to my equals method. Most of this code is from the Core Java Volume 1 Fundamentals and I'm reading through the book to get a refresher but have no clue what to do with the equals method. Is it because it's a Person
Class. First I tried putting the putting a different name and salary on the 3 person in the Person Array. I was still getting false. And then I switch it to the same name and still got false. I don't always understand the debugging tool but I thought it looked like the problem was with my return statement.
package v1ch05.abstractClasses;
public class PersonTest
{
public static void main(String[] args)
{
var people = new Person[3];
// fill the people array with Student and Employee objects
people[0] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
people[1] = new Student("Maria Morris", "computer science");
people[2] = new Employee("Harry Hacker", 50000, 1989, 10, 1);
// print out names and descriptions of all Person objects
for (Person p : people)
System.out.println(p.getName() + ", " + p.getDescription());
boolean isEmployee = people[0].equals(people[2]);
System.out.println("Is Employee:" + isEmployee);
}
}
package v1ch05.abstractClasses;
import java.time.*;
import java.util.Objects;
public class Employee extends Person
{
private double salary;
private LocalDate hireDay;
public Employee(String name, double salary, int year, int month, int day)
{
super(name);
this.salary = salary;
hireDay = LocalDate.of(year, month, day);
}
public double getSalary()
{
return salary;
}
public LocalDate getHireDay()
{
return hireDay;
}
public String getDescription()
{
return String.format("an employee with a salary of $%.2f", salary);
}
public void raiseSalary(double byPercent)
{
double raise = salary * byPercent / 100;
salary += raise;
}
@Override
public boolean equals(Object otherObject) {
if(this == otherObject) return true;
if(otherObject == null) return false;
if(getClass() != otherObject.getClass()) return false;
Employee other = (Employee) otherObject;
return super.equals(other)
&& salary == other.salary
&& Objects.equals(hireDay, other.hireDay);
}
}
package v1ch05.abstractClasses;
public abstract class Person
{
public abstract String getDescription();
private String name;
public Person(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
@Override
public boolean equals(Object otherObject) {
if(this == otherObject) return true;
if(otherObject == null) return false;
if(getClass() != otherObject.getClass()) return false;
Person other = (Person) otherObject;
return name == other.name;
}
}