Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

issue with java late binding and method overload

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading