0

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)?

1 Answer 1

5

(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.

Sign up to request clarification or add additional context in comments.

7 Comments

why would i ever intentionally pass a null to new Empolyee().equals(null). is if(obj == null) return false; written to cover all the possibilities?
@user133: it has nothing to do with "intentionally". You can't control how the method is used since it's public.
@user133466: 1st, HoverfraftFullOfEels is correct. 2nd- this scenario is very much possible. Imagine you have a Map<Integer,Employee>. Now you do myEmployee.equals(myMap.get(5));. If myMap does not contain 5 as a key, it will return null.
what does this notation mean Map<Integer,Employee> ? and why does it matter if the method is public?
@user133466: This (Map<Integer,Employee>) is a java data structure for a map. You will probably get to it later in your studies - no need to rush. The method must be public because it is how it was declared in Object - and you cannot reduce the visibility of a method.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.