Look at this piece of code.
Father Father = new Son ();
The parent class reference points to the subclass object, which is the Java Polymorphism feature, which has a polymorphic lead to dynamic binding, how to introduce it, see this code:
classfather{PrivateString namestring; Public voidspeak () {System.out.println ( This. GetClass () + "Parent class my Name is:" + This. namestring); } PublicFather () {}; PublicFather (String namestring) { This. namestring =namestring; }}classSonextendsfather{PrivateString namestring; PublicSon (String namestring) { This. namestring =namestring; } Public voidspeak () {System.out.println ( This. GetClass () + "Subclass My name is:" + This. namestring); }}
Father Father = new Son ("Huangshan");
Father.speak ();
The result of the execution is
Class son subclass my name is: Huangshan
The parent class reference is defined, but this reference points to the subclass object on the heap son, which executes the speak of the subclass and does not execute the parent class. The so-called dynamic binding refers to this:
Method is determined at run time according to the object to which it is directed.
This is my understanding.
Static bindings:
As opposed to dynamic binding is static binding, so-called static binding is the method is determined before the program runs. The static binding of Java can be easily understood as binding during program compilation. In Java, only Final,static,private and constructor methods are static bindings.
Dynamic binding and static binding another argument is that early binding and late binding.
It can be seen that the upward transformation and polymorphism of Java are implemented by dynamic binding. The language implements late binding, and it must provide mechanisms to determine the type of the object during run time and to invoke the appropriate method, respectively.
Dynamic binding is for methods only and not for properties:
See Program:
Public classJavadt {/** * @paramargs*/ Public Static voidMain (string[] args) {//TODO Auto-generated method stubsFather Father =NewSon (); Father.speak ();
System.out.println (father.namestring);
}}classfather{ PublicString namestring = "Parent Class Property"; Public voidspeak () {System.out.println ( This. GetClass () + "Parent class my Name is:" + This. namestring); } PublicFather () {}; PublicFather (String namestring) { This. namestring =namestring; }}classSonextendsfather{ PublicString namestring = "Subclass Attribute"; Public voidspeak () {System.out.println ( This. GetClass () + "Subclass My name is:" + This. namestring); }}
The execution results are:
Class son subclass my name is: Subclass attribute
Parent Class Property
Father.name reads the properties of the parent class.
If you want to access the parent class property, simply wrap the property into a method.
Dynamic binding of Java