早期绑定:编译器可以在编译时解析的绑定称为静态或早期绑定。所有静态、私有和最终方法的绑定都是在编译时完成的。
例子:
public class NewClass {
public static class superclass {
static void print()
{
System.out.println("print in superclass.");
}
}
public static class subclass extends superclass {
static void print()
{
System.out.println("print in subclass.");
}
}
public static void main(String[] args)
{
superclass A = new superclass();
superclass B = new subclass();
A.print();
B.print();
}
}
输出:
print in superclass.
print in superclass.
后期绑定:在后期绑定或动态绑定中,编译器不决定要调用的方法。覆盖是动态绑定的一个完美例子。在覆盖父类和子类时具有相同的方法。
例子:
public class NewClass {
public static class superclass {
void print()
{
System.out.println("print in superclass.");
}
}
public static class subclass extends superclass {
@Override
void print()
{
System.out.println("print in subclass.");
}
}
public static void main(String[] args)
{
superclass A = new superclass();
superclass B = new subclass();
A.print();
B.print();
}
}
输出:
print in superclass.
print in subclass.
早绑定和晚绑定的区别表:
Early Binding | Late Binding |
---|---|
It is a compile-time process | It is a run-time process |
The method definition and method call are linked during the compile time. | The method definition and method call are linked during the run time. |
Actual object is not used for binding. | Actual object is used for binding. |
For example: Method overloading | For example: Method overriding |
Program execution is faster | Program execution is slower |