Understanding of Java Polymorphism

Source: Internet
Author: User


The polymorphism of Java

Object-oriented programming has three characteristics, namely encapsulation, inheritance and polymorphism.

Encapsulation hides the internal implementation mechanism of the class so that it can change the internal structure of the class without affecting the consumer, while protecting the data.

Inheritance is intended to reuse the parent class code, while preparing for the implementation of polymorphism. So what is polymorphism?

The Overrides, overloads, and dynamic joins of a method are polymorphic. Java introduces the concept of polymorphism, one of the reasons is that it is in the inheritance of the class and C + +, which allows multiple inheritance, which does give it a very powerful function, but the complex inheritance of the C + + developers have also brought greater trouble, in order to avoid the risk, Java only allow single inheritance, There is a is-a relationship between the derived class and the base class (that is, "cat" is a "animal"). Although this ensures that the inheritance relationship is simple and clear, but there is bound to be a large number of functional limitations, so Java introduced the concept of polymorphism to compensate for this shortcoming, in addition, abstract classes and interfaces are also important means to solve the single inheritance restrictions. At the same time, polymorphism is also the essence of object-oriented programming.

To understand polymorphism, you first need to know what is "upward transformation".

I defined a subclass cat, which inherits the animal class, and the latter is the parent class. I can pass

Cat C = new Cat ();
Instantiating a cat object is not difficult to understand. But when I define this:

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

Very simply, it means I have defined a reference to the animal type, pointing to the new cat type object. Because Cat is inherited from its parent class animal, references to animal types can point to objects of the cat type. So what's the point of doing that? Because subclasses are an improvement and an extension to the parent class, the generic subclass is functionally more powerful than the parent class, and the attributes are more unique than the parent class.

An object that defines a reference to a parent class type that points to a subclass can use both the powerful functionality of a subclass and the commonality of the parent class.

Therefore, a reference to a parent class type can invoke all the properties and methods defined in the parent class, and it is helpless for a method that is not in the parent class defined in the subclass;

At the same time, a method in the parent class can be called by a reference to the parent class only if it is defined in the parent class and is not overridden in the subclass.

For a method defined in a parent class, if the method is overridden in a subclass, then a reference to the parent class type invokes this method in the subclass, which is the dynamic connection.

Look at the following procedure:

Class father{
public void Func1 () {
Func2 ();
}
This is the Func2 () method in the parent class, because the method is overridden in the following subclass
So when called in a reference to a parent class type, this method is no longer valid
Instead, the Func2 () method that will be overridden in the calling 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 called by a reference of the parent class type
So in the following Main method, CHILD.FUNC1 (68) is wrong.
public void func1 (int i) {
System.out.println ("BBB");
}
Func2 () overrides the Func2 () method in the parent class father
If the Func2 () method is called in a reference to the parent class type, then this method must be overridden 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 the print result be?
}
}
The above procedure is a very typical polymorphic example. Subclass Child inherits the parent class father and overloads the Func1 () method of the parent class, overriding the Func2 () method of the parent class. The overloaded func1 (int i) and func1 () are no longer the same method, and because there is no func1 (int i) in the parent class, the reference child of the parent class type cannot call the func1 (int i) method. When the subclass overrides the Func2 () method, the reference to the parent class type will call the FUNC2 () overridden in the subclass when calling the method.

So what kind of results will the program print?

Obviously, it should be "CCC".

For polymorphism, it can be summed up as:

One, a reference to the child class using the parent class type;

Second, the reference can only invoke methods and variables defined in the parent class;

Thirdly, if a method in the parent class is overridden in a subclass, the method in the subclass is called when the method is called; (dynamic connection, dynamic invocation)

Variables cannot be overridden (overwritten), the concept of "overriding" is only for methods, and if a variable in the parent class is "overridden" in a subclass, an error is made at compile time.

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

Multi-State detailed (finishing) 2008-09-03 19:29 polymorphism is by:
1 interfaces and implements the interface and overrides several different classes of the same method in the interface embodied by
2 The parent class and the inherited parent class are implemented by overwriting several different subclasses of the same method in the parent class.

First, the basic concept

Polymorphism: Sends a message to an object, allowing the object to decide for itself what behavior to respond to.
A dynamic method call is implemented by assigning a subclass object reference to a superclass object reference variable.

This mechanism of Java follows a principle: When a Superclass object references a variable that references a subclass object, the type of the referenced object rather than the type of the reference variable determines which member method to call, but the method that is called must be defined in the superclass, that is, the method covered by the quilt class.

1. If a is a reference to Class A, then a can point to an instance of Class A, or to a subclass of Class A.
2. If a is a reference to interface A, then a must point to an instance of a class that implements interface A.

Second, Java polymorphism Implementation mechanism

Sun's current JVM implementation mechanism, a reference to a class instance, is a pointer to a handle (handle), which is a pair of pointers:
A pointer to a table, and in fact the table has two pointers (one pointer to a method table containing the object, and another to the class object, indicating the type to which the object belongs);
Another pointer points to a piece of memory space allocated from the Java heap.

Iii. Summary

1. Implement a dynamic method call by assigning a subclass object reference to a superclass object reference variable.

Derivedc c2=new Derivedc ();
BaseClass a1= C2; BaseClass base class, Derivedc is a subclass that inherits from BaseClass
A1.play (); Play () is defined in Baseclass,derivedc, where subclasses overwrite the method

Analysis:
* Why can object instances of a subclass's type be covered by a superclass reference?
Auto-enable up-shift. Through this statement, the compiler automatically moves the subclass instance up to become a generic type baseclass;
* A.play () will execute the subclass or the method defined by the parent class?
Sub-class. At run time, the actual type is referenced according to the object of a to obtain the corresponding method. So there is polymorphism. A base class object reference, which is given a different subclass object reference, behaves differently when the method is executed.

In A1=c2, there are still two handles, A1 and C2, but A1 and C2 have the same chunk of data memory and different function tables.

2. You cannot assign a parent object reference to a child class object reference variable

BaseClass a2=new BaseClass ();
Derivedc c1=a2;//Error

In Java, the upward transformation is automatic, but the downward transformation is not, and requires our own definition to be enforced.
C1= (DERIVEDC) A2; A forced conversion, that is, a downward transformation.

3, remember a very simple and complex rule, a type reference can only reference the reference type itself contains methods and variables.
You might say that the rule is not correct, because the parent class refers to the subclass object, and the last thing you do is subclass the method.
In fact, this is not contradictory, it is because the use of late binding, dynamic operation of the time and according to the type to call the subclass method. If this method of the subclass is not defined in the parent class, an error occurs.
For example, the Derivedc class adds several functions (such as myfun ()) In addition to the functions defined in BaseClass.

Analysis:
When you use a parent reference to refer to a subclass, the JVM has already used the compiler-generated type information to adjust the conversion.
Here you can understand that the equivalent of a function that is not a parent class is set from the virtual function table to be invisible. Note that it is possible that some function addresses in the virtual function table have been rewritten in the subclass, so the virtual function project address in the Object virtual function table has been set to the address of the method body completed in the subclass.

4. Comparison of Java and C + + polymorphism

The JVM support workaround for polymorphism is almost the same as in C + +,
Just a lot of the compiler in C + + is putting type information and virtual function information in a virtual function table, but using some kind of technology to differentiate.

Java opens the type information and function information. After inheritance in Java, subclasses will reset their virtual function tables, and the items in this virtual function table are made up of two parts. Virtual functions that inherit from the parent class and the subclass's own virtual functions.
A virtual function call is called indirectly through a virtual function table, so polymorphism can be achieved.

All of Java's functions, except those declared final, are later bound.

Four. 1 acts, different objects, they are specifically manifested in the way they are not the same,
Example: Method overload overloading and method override (overwrite) override
Class human{
void Run () {The output person is running}
}
Class Man extends human{
void run () {Output man running}
}
This time, the same is run, different objects, not the same (this is the method covered by the example)
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 a different parameter table

OK, understand that these are not enough, but also employing in the running example
Human ahuman=new Man ();
So I'm going to instantiate a man's object and declare a human reference, and let it point to the man object.
It means that the man is the object of human to see.

Like going to the zoo, you see an animal, you don't know what it is, "What kind of animal is this?" "It's a giant panda!"
These 2 words, is the best proof, because do not know it is the panda, but know its parent class is an animal, so,
This Panda object, you see it as the father of the animal look, this looks reasonable.

In this way, notice that the new Man () is instantiated, so the Ahuman.run () method outputs "men running."

If you write some of its unique methods such as Eat () under the subclass man, and human does not have this method,

When calling the Eat method, be sure to force type conversion ((man) Ahuman). Eat (), so you can ...

For the interface, the situation is similar ...

Instance:

Package domatic;

Defining Superclass SuperA
Class SuperA {
int i = 100;

void Fun (int j) {
j = i;
System.out.println ("This is SuperA");
}
}

Defines subclasses of SuperA Subb
Class Subb extends SuperA {
int m = 1;

void fun (int aa) {
System.out.println ("This is Subb");
}
}

Defines subclasses of SuperA SUBC
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);
}
}
/*
* Subb and SUBC are subclasses of superclass SuperA in the above code, we declare 3 reference variables a, B in class test,
* C to implement a dynamic method call by assigning a subclass object reference to a superclass object reference variable. Maybe someone will ask:
* "Why (1) and (2) Not output: This is SuperA".
* This mechanism of Java follows a principle: When a Superclass object references a variable that references a subclass object,
* The type of the referenced object instead of the reference variable determines whose member method is called.
* But this called method must be defined in the superclass,
* That is, the method covered by the quilt class.
* Therefore, do not be confused by the example above (1) and (2), although written A.fun (), but because (1) A is assigned by B,
* Points to an instance of subclass Subb, so (1) the called Fun () is actually the member method of the subclass Subb Fun (),
* It overrides the member method of the superclass SuperA Fun (); similarly (2) the member method of the subclass SUBC is called Fun ().
* Also, if a subclass inherits a superclass that is an abstract class, although the abstract class cannot be instantiated by the new operator,
* However, you can create an object reference to an abstract class that points to a subclass object for run-time polymorphism. The specific implementation of the above example.
* However, subclasses of an abstract class must override all the abstract methods in the implementation superclass,
* Otherwise the subclass must be decorated with the abstract modifier, and of course it cannot be instantiated.
*/
Most of the above are polymorphic by means of subclasses overriding the parent class. Here's another way to implement polymorphism-----------overriding the parent class method

1.JAVA does not have many inheritance, a class can have a parent class. The manifestation of inheritance is polymorphism. A parent class can have more than one subclass, whereas in subclasses you can override the parent class's methods (for example, method print ()) so that the code that is overridden in each subclass is different and the natural representation is different. This uses the parent class's variable to refer to the different subclasses, the result and the representation of the same method print () is different, this is polymorphic, the same message (that is, call the same method) will have the same result. To illustrate:
Parent class
public class father{
Parent class has a child-fighting method
public void Hitchild () {
}
}
Sub-Class 1
public class Son1 extends father{
Overriding parent class hitting kids method
public void Hitchild () {
System.out.println ("Why hit me?") What have I done wrong! ");
}
}
Sub-Class 2
public class Son2 extends father{
Overriding parent class hitting kids method
public void Hitchild () {
System.out.println ("I know wrong, don't fight!" ");
}
}
Sub-Class 3
public class Son3 extends father{
Overriding parent class hitting kids method
public void Hitchild () {
System.out.println ("I run, you can't fight!" ");
}
}

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 ();
}
}
All call the same method, and there are different results! That's how polymorphism behaves!

Understanding of Java Polymorphism

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.