issue with java late binding and method overload

Advertisements

I am just starting out with Java and came cross this code snippet:

class Employee {
    public void setSalary(double salary) {
        System.out.println("Employee.setSalary():" + salary);
    }

    public static void main(String[] args) {
        Employee ken = new Manager();
        int salary = 200;
        ken.setSalary(salary);  // *

    }

}

class Manager extends Employee {
    public void setSalary(int salary) {
        System.out.println("Manager.setSalary():" + salary);
    }
}

According to my understanding of java late binding rule, the line on * should invoke the setSalary of the Manager class because it’s the "runtime type" of ken, but it calls the setSalary of the Employee class. can someone explain what’s is going on here thanks.

>Solution :

Look carefully at the setSalary method in class Employee:

public void setSalary(double salary)

And now look carefully at the setSalary method in class Manager:

public void setSalary(int salary)

Do you see the difference? The one in class Employee takes a double, while the one in class Manager takes an int.

Therefore, the one in class Manager does not override the one in class Employee.

For a method to override a method from a superclass, it must conform to the following rules:

  • The name of the method must be the same
  • The number and types of the parameters must be the same

You could have caught this error if you had used the @Override annotation in class Manager:

class Manager extends Employee {
    @Override
    public void setSalary(int salary) {
        System.out.println("Manager.setSalary():" + salary);
    }
}

By using the @Override annotation, you tell the compiler that the method is supposed to override a method from its superclass. If it doesn’t, then the compiler will give you an error.

Leave a ReplyCancel reply