Reputation: 3415
suppose we have a class Employee with the following data field and function. The program attempts to see if 2 Employees
are equal by comparing their name
and address
public class Employee{
private String name;
private double hours;
private double rate;
private Address address;
@Override
public boolean equals(Object obj){
if(obj == this) return true;
if(obj == null) return false;
if(this.getClass() == obj.getClass()){
Employee other = (Employee) obj;
return name.equals(other.name) && address.equals(other.address);
}else{
return false;
}
}
why didn't we do this instead public boolean equals(Employee obj)
(different parameters)?
Upvotes: 0
Views: 91
Reputation: 178451
(1) if you do new Empolyee().equals(null)
- this will happen.
(2) Because the Object
class declared equals(Object)
- and you cannot put Employee
as a parameter in order to override this method. You can only widen the parameter when overriding a method, never narrow it.
What will happen if you then do:
Object o = new Employee();
o.equals(new Object());
The "method" will have no idea how to handle this case, while it is perfectly valid and cannot be known (in the general case) in compile time.
To avoid it, this type of variance is not allowed when overriding a method, and you will get a compilation error if you try to do it.
Upvotes: 5