Understanding Method Binding in Java

Method binding is a mechanism of associating a method call in Java code to the declaration and implementation of the method being called. When we mention the phrase “declaration of the method”, we are referring to the method signature, which consists of the method name, and the order and the data type of its parameters. When we mention the phrase “implementation of the method”, we are referring to the body of the method that executes at runtime as part of the method call.

The compiler always decides the signature of the called method. Depending on the method type (static, non-static, and interface), the compiler or the runtime decides what implementation of the method is executed at runtime.

Let us consider three Java programs listed in Listing 1, Listing 2, and Listing 3.

Listing 1: An Employee class

// Employee.java
package com.jdojo.blogs.methodbinding;

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

Listing 2: A Manager class

// Manager.java
package com.jdojo.blogs.methodbinding;

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

Listing 3: A Test class to test method binding

// Test.java
package com.jdojo.blogs.methodbinding;

public class Test {
    public static void main(String[] args) {
        /* Create a Manager object and assign its reference to a
           variable emp of the Employee type
         */
        Employee emp = new Manager();

        /* Call the setSalary() method */
        int salary = 12000;
        emp.setSalary(salary); /* Which setSalary() method is called.
                                  Employee.setSalary() or Manager.setSalary() */
       }
}

Output:

Can you tell what is printed when the Test class is run?

Click here to read the complete post.

Downloads