A word summary, see do not understand the following code:
The declared object is an object of the parent class (superclass), but the actual memory point is the instance of the subclass new.
If the parent class object invokes a method (for example, ToString) and the subclass does not override this method, the parent class (ToString) method is invoked.
If the subclass overrides this method (ToString), it invokes the ToString method of the subclass.
Code address: Point I download
Code Test one: Test subclasses without overriding the parent class (toString)
/** *
Parent class
* @author SWM * *
/Public
class Superclass {
@Override public
String toString () {return
"superclass tostring" + "----" + "class name of the current calling ToString Method:" + This.getclass ()
. GetName ();
}
/**
* Sub Class
* @author SWM
*
*/
public class subclass extends superclass {
@Override
Public String toString () {
Return "Subclass ToString" + "----" + "class name of the current call tostring method" + This.getclass (). GetName ();
// }
}
/**
* Test class
* @author SWM
*
*/
public class Executetest {
public static void Main (string[] args) {
New subclass instance, assigned to the declared parent class object
Superclass superclass = new subclass ();
Superclass Object Invoke ToString
System.out.println (Superclass.tostring ());
}
}
Printed log: Superclass's tostring----The name of the class that currently calls the ToString method: Test. Subclass
As you can see from the log, the superclass ToString method is invoked, but the actual calling class is: Subclass (Subclas)
Code Test Two: subclasses override the Parent class's method (toString) Situation--that is, the annotation of the handle class is removed and nothing else changes.
/**
* Sub Class
* @author SWM
*
*/
public class subclass extends superclass {
@Override
Public String toString () {
Return "Subclass ToString" + "----" + "class name of the current call tostring method" + This.getclass (). GetName ();
}
}
Printed log: Subclass's ToString----class name test that currently calls the ToString method. Subclass
As you can see, the method that the parent object invokes is the method after the subclass overrides
Do not understand the comments addressed.