Subclass to Parent class (parent class reference to child class object)
A subclass can be converted to a parent class, with the following parent class Fruittest and its subclasses appletest
class fruittest { = "Fruittest"; Public String get () {return str;} Public void Set (String str) {this. str = str;}} class extends fruittest { = "Appletest";}
fruittest obj = new Appletest (); is right.
The obj.str result is "fruittest", not str ("Appletest") in the subclass. The property variables of obj are all parent classes.
Obj.get () Gets the "fruittest" that executes the method in the parent class, but if the subclass overrides the parent class method, the child class is the method
class extends fruittest { = "Appletest"; Public String get () {return str;};}
Then Obj.get () gets the "Appletest".
Summary: A subclass can be converted to a parent class, that is, a parent class reference to a child class object. The referenced property is the parent class, and the method is a subclass if the quilt class overrides it.
Parent class Rotor Class (subclass reference to parent class object)
The parent class cannot be converted directly to a subclass, appletest obj = new Fruittest (); Is wrong.
Appletest obj = (appletest) new Fruittest (); The compile time will also error.
Fruittest obj = new Appletest ();
Appletest test = (appletest) obj; These two sentences are correct.
If the parent class is converted to a child class, the parent class reference must point to a subclass object. Essentially, a parent class reference to a child class object is changed to a child class reference.
Java Subclass parent classes convert to and from each other