Difference between parent class xx = new subclass () and subclass xx = new subclass ()

Source: Internet
Author: User

In java, we often encounter the definition object of the parent class xx = new subclass (). What is the difference between it and the subclass xx = new subclass ()? Let's analyze the code below:

Package com. sky. java;


Public class FatherNewSon
{


/**
* @ Param args
*/
Public static void main (String [] args)
{
// TODO Auto-generated method stub
A ta = new B ();
B tb = new B ();
Ta. test ();

Tb. test ();
Tb. son ();
}


}
Class {
Public ()
{
 
}
Public void test ()
{
System. out. println (this. getClass (). getName ());
}
}


Class B extends {
Public B ()
{

}
Public void son ()
{
System. out. println ("son ");
}
}

In this example, ta is referenced by the parent class pointing to the subclass object, and tb is defined by the subclass xx = new subclass (). However, ta. son () returns an error: This method is not available, but tb. son () does not report an error. It can be seen that the object defined by the parent class xx = new subclass () cannot call methods that are not inherited from the parent class. In addition, the running result is as follows:


It can be seen that both ta. test () and tb. test () call methods in B.

The above section summarizes the differences between the parent class xx = new subclass () and the subclass xx = new subclass:

1. objects defined by the parent class xx = new subclass () can only call inherited methods.

2. The object defined by the parent class xx = new subclass () calls the subclass method instead of the parent class.

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.