Learn more about parent class references pointing to child classes, and learn more about references pointing

Source: Internet
Author: User

Learn more about parent class references pointing to child classes, and learn more about references pointing

The parent class application points to a subclass object and refers:

The parent class Animal, subclass Cat, Dog. Here, Animal can be an interface or class, and Cat and Dog are subclasses that inherit or implement Animal.

Animal animal = new Cat ();

The declared parent class actually points to the subclass object. Let's first understand from the memory perspective.

Assume that the Aninal parent class uses 1 MB for its variables, and its subclasses Dog and Cat need to use MB of memory.


View memory allocation through code:

Animal animal = newAnimal (); // The system will allocate 1 MB of memory

Catcat = new Cat (); the system will distribute MB of memory! Because the subclass has a hidden reference, super points to the parent class instance. Therefore, a parent class will be instantiated before the subclass is instantiated. Execute the parent class constructor first. Because the instance contains the parent class, s can call the method of the parent class.

Cat cat1 = cat, pointing to the 1.5M memory.

Animal animalOne = (Animal) cat; // at this time, animalOne points to 1 MB memory in MB, while animalOne only points to the parent class instance object of the cat instance. Therefore, the animalOne function calls the method of the parent class and cannot call the subclass method (stored in MB memory). Cat cat2 = (Cat) animal // ClassCatException is reported during running. Because animal only has 1 MB of memory, and sub-class references must have MB of memory, it cannot be converted.

Cat cat3 = (Cat) animalOne; // This statement can be run. At this time, s3 points to the MB memory. because f1 is converted from s, it has MB of memory, but it only points to 1 MB of memory.

The above is analyzed from the memory perspective.


From the object perspective

Let's take a look at several keywords:Polymorphism, dynamic link, and upward Transformation

Encapsulation: Hides the internal implementation mechanism of the class. You can modify the internal structure of the class without affecting the user and protect the data;

Inheritance: To reuse the parent class code, the Child class inherits the parent class and has members of the parent class.

Method rewriting, overloading, and dynamic connectionPolymorphism. To understand polymorphism, you must first understand "upward transformation" (subcategories are converted to parent classes ).

Defines a subclass Cat, which inherits the Animal class, and the latter is the parent class. You can use Catc = new Cat (); to instantiate a Cat object, which is not hard to understand. But when I define it like this: Animal a = new Cat (); what does this mean? It indicates that I have defined an Animal type reference pointing to the newly created Cat type object. Since Cat inherits its parent class Animal, the reference of the Animal type can point to the Cat type object. This is "upward transformation ".

So what is the significance of this?

Because subclass is an improvement and extension of the parent class, it is generally more powerful than the parent class in terms of functionality and has more unique attributes than the parent class, defining a reference of a parent class pointing to an object of a subclass can both use the powerful functions of the subclass and extract the commonalities of the parent class. Therefore, the reference of the parent class can call all attributes and methods defined in the parent class. For methods defined in the subclass but not in the parent class, the parent class reference cannot be called;

◆ What is dynamic link?

When the subclass of the parent class method is override, the parent class is called. If the subclass overrides the parent class method, the subclass method is called. This is a dynamic connection.

Class Father {Public void func1 () {Func2 ();} Public void fun2 () {System. out. println ("AAA") ;}} Class Child extends Father {Publlic void func1 (int I) {System. out. println ("BBB");} Public void func2 () {System. out. println ("CCC") ;}} Public class Test {Public static void mian (String [] args) {Father child = new Child (); child. func1 (); // What will be the result? Child. func1 (89 );}}

The above program is a typical example of polymorphism. Child inherits the parent class Father, reloads the func1 () method of the parent class, And overwrites the func2 () method of the parent class. The overloaded func1 (inti) and func1 () are no longer the same method. Because the parent class does not have func1 (int I, the reference child of the parent class cannot call the func1 (inti) method. The subclass overrides the func2 () method, so the reference child of the parent class will call func2 () in the subclass when calling this method ().

So what kind of results will the program print? Apparently,It should be"CCC".


Summary:

Through the above two methods, we understand that the parent class references the Child class, which is actually a multi-state application, reflected in the following points:

  • Use the reference of the parent class to point to the object of the subclass.
  • This reference can only call methods and variables defined in the parent class.
  • If a method in the parent class is rewritten in the subclass, the method in the subclass is called when the method is called. (dynamic connection and dynamic call)
  • Variables cannot be overwritten. The "Override" concept only applies to methods. If the "Override" is used to override the variables in the parent class in the subclass, an error is reported during compilation.

 


In java, the parent class Object references a subclass object.

This is the note I took when I learned "polymorphism" a long time ago.
Here you are! Hope to be useful to you!

Java Polymorphism

Object-Oriented Programming has three features: encapsulation, inheritance, and polymorphism.

The internal implementation mechanism of the class is hidden, so that the internal structure of the class can be changed without affecting the user and data is protected.

Inheritance is designed to reuse the parent code and to implement polymorphism. So what is polymorphism?

Method rewriting, overloading, and dynamic connection constitute polymorphism. One of the reasons why Java introduces the concept of polymorphism is that it is different from C ++ in class inheritance. The latter allows multi-inheritance, which indeed brings a very powerful function to it, however, the complex inheritance relationships also cause greater trouble for C ++ developers. To avoid risks, Java only allows single inheritance, the relationship between the derived class and the base class is IS-A (that is, "cat" is a "animal "). Although this ensures that the inheritance relationship is simple and clear, it is bound to have a lot of functional limitations. Therefore, Java introduces the concept of polymorphism to make up for this deficiency. In addition, abstract classes and interfaces are also an important means to solve the limitation of single inheritance. At the same time, polymorphism is also the essence of object-oriented programming.

To understand polymorphism, we must first know what is "upward transformation ".

I have defined a subclass Cat, which inherits the Animal class, and the latter is the parent class. I can use

Cat c = new Cat ();
It is not hard to understand how to instantiate a Cat object. But when I define it like this:

Animal a = new Cat ();
What does this mean?

It means that I have defined an Animal type reference, pointing to the newly created Cat type object. Since Cat inherits its parent class Animal, the reference of the Animal type can point to the Cat type object. So what is the significance of this? Because subclass is an improvement and extension of the parent class, it is generally more powerful than the parent class in terms of functionality and has more unique attributes than the parent class,

Defining a reference of a parent class pointing to an object of a subclass can both use the powerful functions of the subclass and extract the commonalities of the parent class.

Therefore, the reference of the parent class can call all the attributes and methods defined in the parent class, but it is helpless for the methods defined in the Child class but not in the parent class;

At the same time, a method in the parent class can be referenced and called by the parent class only when it is defined in the parent class but not overwritten in the subclass;

For methods defined in the parent class, if this method is rewritten in the subclass, the reference of the parent class type will call this method in the subclass, which is a dynamic connection.

Take a look at the following program:

Class Father {
Public void func1 (){
Func2 ();
}
// This is the func2 () method in the parent class, because this method is rewritten in the subclass below
// This method will no longer be valid when called in the reference of the parent class type
// Replace it with the func2 () method that is rewritten in the call subclass.
Public void func2 (){
System. out. println ("AAA ");
}
}

Class Child extends Father {
// Func1 (int I) is an overload of the func1 () method.
// Because this method is not defined in the parent class, it cannot be referenced and called by the parent class.
// In the following main method, child. func1 (68) is incorrect.
Public void func1 (int I ){
System. out. println ("BBB ");
}
// Func2 () overwrites the parent ...... the remaining full text>

How can I understand the reference of a parent class pointing to a subclass object?

Although the parent class can only be used, the results can be different, because the methods of the parent class can be rewritten in the subclass. When the reference of the parent class points to the instance of the subclass, he calls the subclass to override the parent class method to produce different results.

Class Father {

Private String name;

Public Father (){}
Public Father (String name ){
This. name = name;
}

Public String getName (){
Return this. name;
}
Public void getMessage (Father F ){

System. out. println ("New Year's Day holiday, specific days and sub-classes are determined based on your actual situation ");
}
}

Class son1 extends Father {
Public son1 ()
{
}

Public son1 (String name ){
Super (name );
}
Public void getMessage (Father F ){

System. out. println (F. getName () + "New Year's Day holiday, subclass 1 holiday for 2 days ");
}

}

Class son2 extends Father {
Public son2 ()
{
}
Public son2 (String name ){
Super (name );
}
Public void getMessage (Father F ){

System. out. println (F. getName () + "New Year's Day holiday, subclass 2 3 days off ");
}

}

Public class Test {

Public static void main (String [] s ){

Father F = new Father ();

F. getMessage (F );

F = new son1 ("son1 ");

F. getMessage (F );

F = new son2 ("son2 ");

F. getMessage (F );

System. out. println ("-----------------------------------");

Son1 s1 = new son1 ("son1 ");

S1.getMessage (s1 );

Son2 s2 = new son2 ("son2 ");

S2.getMessage (s2 );

// Do you know the parameters of the getMessage () function? The parameter type is the parent class, but you can pass it in as a subclass object. Why is this possible, because the reference of the parent class can point to the object of the subclass?
}
}... Remaining full text>

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.