Home > Enterprise >  issue with java late binding and method overload
issue with java late binding and method overload

Time:07-26

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.

CodePudding user response:

Your understanding is correct.

Except that the method public void setSalary(int salary) in class Manager is not overriding the method public void setSalary(double salary), because double and int are two different types.

Declare public void setSalary(double salary) in the class Manager and it will work as you expect.

Little tip: use @Override annotation on overridden methods. If you were doing so, you would have spotted the issue right after.

CodePudding user response:

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.

  •  Tags:  
  • java
  • Related