It is well known that Java handle and C + + Ponter instead of object, we are familiar with C + + 's parent class pointer call the subclass entity example, Then the Java handle is also possible?
here, Let me give you an example.
classfather{ public voidannounce () {System.out.println ("Father"); }}classChildextendsFather{@Override public voidannounce () {System.out.println ("child"); }} public classHello { public Static voidmain (string[] Args) {System.out.println ("Hello"); Father Father=Newchild (); Father.announce (); }}
In this code, we assign the object of a subclass to the handle of the parent class, and then call the method that has been overloaded with the quilt class, and we get the following result:
Hello
Child
As we can see, using this parent class handle, we are actually calling the announce method of the Subclass. Knowing this feature can be a matter of fact.
Here we are going to introduce a concept: dynamic invocation
Dynamic linking means that when a method is implemented only in the parent class and not implemented in a subclass, we call the method in the parent class. And when a method is implemented in both the parent and subclass, we call the Subclass's method regardless of the type of Handle. however, This method must be defined in the parent class, otherwise it cannot be called by the parent class Handle.
It is also important to note that Java can be automatically transformed, that is, you can assign a class object to the parent class handle< but not automatically downward transformation, the method of downward transformation needs to be defined Manually.
Java Parent class object calls subclass Entity: method override vs. Dynamic Call