What is the mechanism for implementing polymorphism in Java?

Source: Internet
Author: User

Object-oriented programming has three main characteristics: encapsulation, inheritance, polymorphism.

Encapsulation hides the internal implementation mechanism of the class, and can change the internal structure of the class without affecting the use, while protecting the data. To the outside, its internal details are hidden, and what is exposed to the outside world is the way it is accessed.

Inheritance is to reuse the parent class code. Two classes can use inheritance if they have a is-a relationship.

Polymorphism means that the specific type of reference variable defined in the program and the method call issued through the reference variable are not defined programmatically. It is only when the program is running that a reference variable will point to the instance object of which class, and the method called by the reference variable is the method implemented in which class. Must be determined by the time the program is run. Because the specific class is determined when the program is run, in this way, without modifying the source code, the reference variable can be bound to a variety of different class implementations, which causes the specific method of the reference call to change, that is, without modifying the program code can change the code that the program is bound to, so that the program can select multiple running states, This is polymorphism.


But there are some drawbacks to the upward transition, which is that it will inevitably lead to the loss of some methods and properties, which we cannot acquire. Therefore, a reference to a parent class type can call all the properties and methods defined in the parent class, and it will be a little too different for methods and properties that exist only with subclasses.


Class Wine {
public void Fun1 () {
System.out.println ("Wine's Fun ...");
Fun2 ();
}

public void fun2 () {
System.out.println ("Wine's Fun2 ...");
}
}


Class JNC extends wine{
/**
* @desc Subclass Overload Parent class method
* The method is not present in the parent class, and the parent class cannot refer to the method's
* @param a
* @return void
*/
public void Fun1 (String a) {
System.out.println ("JNC's Fun1 ...");
Fun2 ();
}

/**
* Subclass overrides Parent class method
* When referring to a subclass's parent class reference call Fun2, the method must be called
*/
public void fun2 () {
System.out.println ("JNC's Fun2 ...");
}
}

public class Test24 {
public static void Main (string[] args) {
Wine a = new JNC ();
A.fun1 ();
}
}

Analysis: In this program the neutron class JNC overloaded the parent class wine Method Fun1 (), Overrides Fun2 (), and the overloaded fun1 (String a) and fun1 () are not the same method, because there is no such method in the parent class, and the method is lost when the transition is up. Therefore, the wine type reference that executes JNC cannot refer to the FUN1 (String a) method. While the subclass Jnc overrides Fun2 (), the wine reference to JNC invokes the Jnc () method in Fun2.

So for polymorphism we can summarize the following:

The parent class reference to a subclass is not available, even if it is overloaded, because it has only access to methods and properties that are owned in the parent class, and to methods that do not exist in the parent class in a subclass. If a subclass overrides some methods in the parent class, when the methods are invoked, they must be using the methods defined in the subclass (dynamic connection, dynamic invocation).

Polymorphism is divided into compile-time polymorphism and Run-time polymorphism. In which the polymorphic is static, mainly refers to the method of overloading, it is based on the different parameters of the list of different functions, through the edit will become two different functions, in the runtime is not polymorphic. The Run-time polymorphism is dynamic, and it is implemented by dynamic binding, which is what we call polymorphism.

Multi-State implementation

Java implementation polymorphism has three prerequisites: inheritance, rewriting, and upward transformation.

Inheritance: Subclasses and parent classes that have inheritance relationships must exist in polymorphism.

Overrides: Subclasses redefine some methods in the parent class, calling methods of subclasses when they are called.

Transition upward: In polymorphism, a reference to a subclass needs to be assigned to the parent class object, only so that the reference can have the method of invoking the method and subclass of the parent class.

Only if the above three conditions are met can we use unified Logic implementation code in the same inheritance structure to handle different objects to perform different behaviors.

For Java, its polymorphic implementation mechanism follows a principle: When a Superclass object references a variable referencing a subclass object, the type of the referenced object, rather than the type of the reference variable, determines whose member method to invoke, but the invoked method must be defined in the superclass, that is, the method overridden by the quilt class.

Implementation form:

In Java, there are two forms of polymorphism that can be implemented. Inheritance and interfaces.

Class a{
Public String Show (D obj) {
Return ("A and D");
}
Public String Show (A obj) {
Return ("A and a");
}
}
Class B extends a{
Public String Show (B obj) {
Return ("B and B");
}
Public String Show (A obj) {
Return ("B and A");
}
}
Class C extends b{}
Class D extends b{}
public class Test25 {
public static void Main (string[] args) {
A a1=new a ();
A a2=new B ();
b b=new B ();
C c=new C ();
D d=new D ();

System.out.println ("1--" +a1.show (b));
System.out.println ("2--" +a1.show (c));
System.out.println ("3--" +a1.show (d));
System.out.println ("4--" +a2.show (b));
System.out.println ("5--" +a2.show (c));
System.out.println ("6--" +a2.show (d));
System.out.println ("7--" +b.show (b));
System.out.println ("8--" +b.show (c));
System.out.println ("9--" +b.show (d));
}
}

The results are:

1--a and A
2--a and A
3--a and D
4--b and A
5--b and A
6--a and D
7--b and B
8--b and B
9--a and D

When a superclass object references a variable referencing a subclass object, the type of the referenced object, rather than the type of the reference variable, determines whose member method to invoke, but the invoked method must be defined in the superclass, that is, the method overridden by the quilt class. This sentence is a generalization of polymorphism. In fact, the invocation of an object method in the inheritance chain has a priority: This.show (O), Super.show (O), This.show (Super) O, Super.show (Super) O).

First we analyze 5,a2.show (c), A2 is a reference variable of type A, so this represents A,a2.show (c), which is found not found in Class A, and is found in the superclass of a (super), because A has no superclass (except object), so skip to the third level, That is, This.show ((Super) O), C has a super Class B, A, so (super) O is B, A,this is also a, here in a find show (a obj), and since A2 is a reference to Class B and Class B overrides show (a obj), Therefore, the show (a obj) method of subclass B is eventually called, and the result is B and a.

Method has been found, but we still have a little doubt here, let's just say this: When a superclass object refers to a variable referencing a subclass object, the type of the referenced object, not the type of the reference variable, determines whose member method to invoke, but the called method must be defined in the superclass. That is to say, the quilt class covers the method. Here we use an example to illustrate what this sentence means: A2.show (b);

Here A2 is a reference variable, is a type A, it refers to a B object, so according to the above sentence means that there is B to determine who to call the method, so A2.show (b) should be called Show (b obj) in B, the resulting result should be "B and B", But why is it different from the previous running results? Here we ignore the following sentence "but the method called here must be defined in the superclass", so show (B obj) exists in Class A. It doesn't exist at all. So this sentence does not apply here. So this is the wrong sentence. Not too. In fact, this sentence also implied that this sentence: it is still in the inheritance chain to call the priority of the method to confirm. So it finds show (a obj) in Class A and because B overrides the method, it calls the method in class B, or it calls the method in Class A.

So the principle of polymorphic mechanism is summarized as follows: When a superclass object references a variable referencing a subclass object, the type of the referenced object, rather than the type of the reference variable, determines whose member method to invoke, but the invoked method must be defined in the superclass, that is, the quilt-covered method, However, it still has to confirm the method based on the precedence of the method call in the inheritance chain: This.show (O), Super.show (O), This.show (Super) O, Super.show (Super) O).

Related Article

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.