Java Reference
In-Depth Information
Binding
Classes have methods and fields; we write code to access them as follows. Assume that myMethod() and xyz are
members of the MyClass class, which is the declared type of the myObject reference variable.
MyClass myobject = get an object reference;
myObject.myMethod(); // Which myMethod() to call?
int a = myObject.xyz; // Which xyz to access?
Binding is the process of identifying the accessed method's code ( myMethod() in this case) or the field ( xyz in this
case), which will be used when the code executes. In other words, binding is a process of making a decision, which
method's code or field will be accessed, when the code executes. There are two stages where the binding can happen:
compile time and runtime. When the binding occurs at compile time, it is known as early binding. Early binding
is also known as static binding or compile-time binding. When the binding occurs at runtime, it is known as late
binding. Late binding is also known as dynamic binding or runtime binding.
Early Binding
Early binding is simple to understand compared to late binding. In early binding, the decision about which method
code and field will be accessed is made by the compiler at compile time. For a method call, the compiler decides
which method from which class will be executed when the code having the method call is executed. For a field access,
the compiler decides which field from which class will be accessed when the code having the field access is executed.
Early binding is used for the following types of methods and fields of a class in Java:
All types of fields: static and non-static
Static methods
In early binding, a method or a field is accessed based on the declared type (or compile-time type) of the variable
(or expression) accessing the method or the field. For example, if early binding is used for an a2.m1() method call,
if a2 has been declared of type A , the m1() method in class A will be called when a2.m1() is executed.
Let's look at a detailed example that demonstrates the early binding rules. Let's consider two classes listed in
Listing 16-6 and Listing 16-7.
Non-static final methods
Listing 16-6. An EarlyBindingSuper Class That Has a Static Field, an Instance Field, and a Static Method
// EarlyBindingSuper.java
package com.jdojo.inheritance;
public class EarlyBindingSuper {
// An instance variable
public String str = "EarlyBindingSuper";
// A static variable
public static int count = 100;
public static void print() {
System.out.println("Inside EarlyBindingSuper.print()");
}
}
 
Search WWH ::




Custom Search