Java polymorphism details -- parent class references subclass objects

Source: Internet
Author: User

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 () overrides the func2 () method in the parent Father class.

// If the func2 () method is called in the reference of the parent class type, this method must be rewritten in the subclass.

Public void func2 (){

System. out. println ("CCC ");

}

}

Public class PolymorphismTest {

Public static void main (String [] args ){

Father child = new Child ();

Child. func1 (); // what will be the printed result?

}

}

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 (int I) and func1 () are no longer the same method. Because the parent class does not contain func1 (int I, if the parent class references child, the func1 (int I) method cannot be called. 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?

Obviously, it should be "CCC ".

For polymorphism, we can conclude that:

1. Use the reference of the parent class to point to the object of the subclass;

2. This reference can only call methods and variables defined in the parent class;

3. If a method in the parent class is rewritten in the subclass, the method in the subclass will be called when the method is called. (dynamic connection and dynamic call)

4. Variables cannot be overwritten. The "Override" concept is only applicable to methods. If the "Override" is applied to the variables in the parent class in the subclass, an error is reported during compilation.

**************************************** **************************************** **************************************** ****

Polymorphism explanation (sorting) 2008-09-03 polymorphism is through:

1. The interface and the implemented interface overwrite several different classes of the same method in the interface.

2. The implementation of the parent class and several different sub-classes that inherit the parent class and overwrite the same method in the parent class.

I. Basic Concepts

Polymorphism: Send a message to an object so that the object determines the action to respond.

You can call a dynamic method by assigning a subclass object reference to a variable referenced by a superclass object.

This mechanism of java follows the principle that when a super-Class Object references a variable to reference a subclass object, the type of the referenced object rather than the type of the referenced variable determines who calls the member method, however, the called method must have been defined in the superclass, that is, the method covered by the quilt class.

1. If a is A reference of Class a, A can point to an instance of class A or a subclass of Class.

2. If a is A reference of interface a, A must point to an instance of a class that implements interface.
II. Implementation Mechanism of Java Polymorphism

SUN's current JVM implementation mechanism, class instance reference is to point to a handle pointer, this handle is a pair of pointers:

A pointer points to a table. In fact, this table also has two pointers (one pointer points to a method table containing objects, and the other points to class objects, indicating the type of the object );

The other Pointer Points to the memory space allocated from the java heap.

Iii. Summary

1. assign a subclass object reference value to a superclass object to reference a variable to call a dynamic method.

DerivedC c2 = new DerivedC ();

BaseClass a1 = c2; // BaseClass base class. DerivedC is a subclass inherited from BaseClass.

A1.play (); // play () is defined in BaseClass and DerivedC. This method is overwritten by the subclass.

Analysis:

* Why can an object instance of the subclass type be overwritten with a superclass reference?

Automatic upward transformation. With this statement, the compiler automatically moves the subclass instance up to become a general type BaseClass;

* A. play () will execute subclass or parent class definition methods?

Subclass. During runtime, the corresponding method is obtained based on the actual type referenced by the object. So there is polymorphism. Objects of a base class are referenced by different subclass objects. Different actions are performed when this method is executed.

When a1 = c2, there are still two handles, a1 and c2, but a1 and c2 have the same data memory block and different function tables.

2. You cannot reference a parent class object to a subclass object to reference a variable.

BaseClass a2 = new BaseClass ();

DerivedC c1 = a2; // Error

In java, upward transformation is automatically performed, but downward transformation is not. We need to define it as mandatory.

C1 = (DerivedC) a2; forced conversion, that is, downward transformation.

3. Remember a simple and complex rule. A type reference can only reference methods and variables contained in the reference type.

You may say that this rule is incorrect, because when the parent class references a subclass object, the method of the subclass is executed.

In fact, this is not a conflict, because later binding is adopted, and the subclass method is called according to the type during dynamic operation. If the subclass method is not defined in the parent class, an error occurs.

For example, in addition to inheriting the functions defined in BaseClass, The DerivedC class also adds several functions (such as myFun ())

Analysis:

When you use the parent class to reference and point to a subclass, the jvm has actually used the type information generated by the compiler to adjust and convert the type information.

As you can understand, it is equivalent to setting functions not contained in the parent class to invisible from the virtual function table. Note that some function addresses in the virtual function table may have been rewritten in the subclass, therefore, the virtual function Project address in the object virtual function table has been set as the address of the method body completed in the subclass.

4. Comparison of Java and C ++ Polymorphism

The jvm solution to support polymorphism is almost the same as that in c ++,

In c ++, many compilers place both type information and virtual function information in a virtual function table, but use some technology to differentiate them.

Java separates the type information and function information. After inheritance in Java, the subclass will reset its own virtual function table. The project in this virtual function table consists of two parts. The virtual functions inherited from the parent class and their own virtual functions of the subclass.

The virtual function is called indirectly through the virtual function table.

All Java functions except those declared as final are bound later.

Iv. One behavior, different objects, is embodied in different ways,

For example, method overload overloading and method override

Class Human {

Void run () {the output is running}

}

Class Man extends Human {

Void run () {output man running}

}

At this time, the same is run, and different objects are different (this is an example of method coverage)

Class Test {

Void out (String str) {output str}

Void out (int I) {output I}

}

This example is a method overload with the same method name and different parameter tables.

Okay. I understand that this is not enough. I am still using examples.

Human ahuman = new Man ();

In this way, I instantiate a Man object, declare a reference to Human, and let it point to Man object.

The object Man is regarded as Human.

For example, if you see an animal at a zoo, you don't know what it is. "What is this animal? "" This is the giant panda! "

The two sentences are the best proof, because I don't know that it is a giant panda, but I know that its parent class is an animal, so,

It's reasonable to think of this giant panda object as its parent.

In this way, pay attention to the new Man (); the Man object is indeed instantiated, so the ahuman. run () method outputs "Man is running"

If you write some unique methods such as eat () under the subclass Man, but Human does not,

When calling the eat method, be sure to force type conversion (Man) ahuman). eat () so that you can...

For the interface, the situation is similar...

Instance:

Package domatic;

// Define superclass superA

Class superA {

Int I = 100;

Void fun (int j ){

J = I;

System. out. println ("This is superA ");

}

}

// Define subB, a subclass of superA

Class subB extends superA {

Int m = 1;

Void fun (int aa ){

System. out. println ("This is subB ");

}

}

// Define subC, a subclass of superA

Class subC extends superA {

Int n = 1;

Void fun (int cc ){

System. out. println ("This is subC ");

}

}
Class Test {

Public static void main (String [] args ){

SuperA a = new superA ();

SubB B = new subB ();

SubC c = new subC ();

A = B;

A. fun (100 );

A = c;

A. fun (200 );

}

}

/*

* In the above Code, subB and subC are subclasses of super class superA. In the Test class, we declare three reference variables a, B,

* C. You can call a dynamic method by assigning a subclass object reference value to a super Class Object reference variable. Someone may ask:

* "Why (1) and (2) are not output: This is superA ".

* This mechanism of java follows the principle that when a super-Class Object references a variable to reference a subclass object,

* The type of the referenced object, rather than the type of the referenced variable, determines who calls the member method,

* However, the called method must have been defined in the superclass,

* That is, the method of quilt coverage.

* Therefore, do not be confused by (1) and (2) in the above example. Although it is written as a. fun (), because a in (1) is assigned a value by B,

* Points to an instance of the subB subclass. Therefore, (1) the called fun () is actually a member method of the subB subclass fun (),

* It overwrites the member method fun () of the superclass superA. Similarly, (2) calls the member method fun () of the sub-class subC ().

* In addition, if the subclass inherits an abstract class, although the abstract class cannot be instantiated through the new operator,

* However, you can create an abstract class object to point to a subclass object to realize Runtime polymorphism. The specific implementation method is the same as above.

* However, The subclass of an abstract class must overwrite all the abstract methods in the super class,

* Otherwise, the subclass must be modified by the abstract modifier and cannot be instantiated.

*/

Most of the above methods implement polymorphism by overwriting the parent class by subclass. The following is another method to implement polymorphism --------- override the parent class Method

1. There is not much inheritance in JAVA, and a class can have a parent class. Inheritance represents polymorphism. A parent class can have multiple sub-classes, while a sub-class can override the method of the parent class (such as the method print (). In this way, the Code rewritten in each sub-class is different, the natural forms are different. In this way, the variables of the parent class are used to reference different sub-classes. When the same method print () is called, the results and representations are different. This is polymorphism, the same message (that is, calling the same method) has different results. Example:

// Parent class

Public class Father {

// The parent class has a method to play the child

Public void hitChild (){

}

}

// Subclass 1

Public class Son1 extends Father {

// Override the parent class child hitting Method

Public void hitChild (){

System. out. println ("Why hit me? What did I do wrong! ");

}

}

// Subclass 2

Public class Son2 extends Father {

// Override the parent class child hitting Method

Public void hitChild (){

System. out. println ("I know the error. Don't hit it! ");

}

}

// Subclass 3

Public class Son3 extends Father {

// Override the parent class child hitting Method

Public void hitChild (){

System. out. println ("I am running, you can't hit it! ");

}

}

// Test class

Public class Test {

Public static void main (String args []) {

Father father;

Father = new Son1 ();

Father. hitChild ();

Father = new Son2 ();

Father. hitChild ();

Father = new Son3 ();

Father. hitChild ();

}

}

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.