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.