Later binding refers to binding according to the type of the object at runtime, also known as dynamic binding or runtime binding. To implement late binding, some mechanism is required to be supported by this so that the type of object can be judged at runtime, and the call overhead is greater than that of previous binding.
The static methods and final methods in Java are early bindings. Subclasses cannot override final methods, and member variables (including static and non-static) are also early bindings. Other methods except static methods and final methods (private belongs to final methods) are later binding, and can determine the type of the object for binding during runtime. The verification procedure is as follows:
The code copy is as follows:
class Base
{
//Member variables, subclasses also have the same member variable name
public String test="Base Field";
// Static methods, subclasses also have static methods with the same signature
public static void staticMethod()
{
System.out.println("Base staticMethod()");
}
//Subclasses will override this method
public void notStaticMethod()
{
System.out.println("Base notStaticMethod()");
}
}
public class Derive extends Base
{
public String test="Derive Field";
public static void staticMethod()
{
System.out.println("Derive staticMethod()");
}
@Override
public void notStaticMethod()
{
System.out.println("Derive notStaticMethod()");
}
//Output the value of the member variable and verify that it is a previous binding.
public static void testFieldBind(Base base)
{
System.out.println(base.test);
}
// Static method, verify that it is a previous binding.
public static void testStaticMethodBind(Base base)
{
//The static method test() from the type Base should be accessed in a static way
//It is more reasonable to use Base.test(). This representation is used here to more intuitively display the early binding.
base.staticMethod();
}
//Call non-static methods and verify that they are late bindings.
public static void testNotStaticMethodBind(Base base)
{
base.notStaticMethod();
}
public static void main(String[] args)
{
Derive d=new Derive();
testFieldBind(d);
testStaticMethodBind(d);
testNotStaticMethodBind(d);
}
}
/*Program output:
Base Field
Base staticMethod()
Derive notStaticMethod()
*/