Java Subclass parent classes convert to and from each other

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.