Binding of variables and methods at compile time and runtime

You can use reference variables of a base class to refer to an object of a derived class. With inheritance, the instance variables bind at compile time and the methods bind at runtime.
Examine the following code:

class Employee {
String name = "Employee";
void printName() {
System.out.println(name);
}
}
class Programmer extends Employee {
String name = "Programmer";
void printName() {
System.out.println(name);
}
}
class Office1 {
public static void main(String[] args) {
Employee emp = new Employee();
Employee programmer = new Programmer();
System.out.println(emp.name);
System.out.println(programmer.name);
emp.printName();
programmer.printName();

Output

Employee
Employee
Employee
Programmer

Let’s see what’s happening in the code, step by step:
■ B creates an object of class Employee, referenced by a variable of its own type—
Employee.
■ c creates an object of class Programmer, referenced by a variable of its base
type—Employee.
■ d accesses variable name defined in class Employee and prints Employee.
■ e also prints Employee. The type of the variable programmer is Employee.
Because the variables are bound at compile time, the type of the object that’s
referenced by the variable emp doesn’t make a difference. programmer.name will
access the variable name defined in the class Employee.
■ f prints Employee. Because the type of the reference variable emp and the type
of object referenced by it are the same (Employee), there’s no confusion with
the method call.
■ g prints Programmer. Even though the method printName is called using a
reference of type Employee, the JRE is aware that the method is invoked on
a Programmer object and hence executes the overridden printName method
in the class Programmer.

Source: OCA Java SE 7 Programmer I Certification Guide Prepare for the  1Z0-803 Exam by by Mala Gupta, Page 329

Leave a Reply

Your email address will not be published. Required fields are marked *