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. , at the same time, inheritance also for the implementation of the foreshadowing of polymorphism. So what is polymorphism? What is the implementation mechanism of polymorphism. Please see me one by one for you to uncover:
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.
For example, you are a wine God, the wine has a unique feeling. One day home to find a few cups inside the table are filled with white wine, from the outside to see that we can not know what is this wine, only after drinking can guess what kind of wine. You drink, this is Jiannanchun, again drink this is Wuliangye, again drink this is alcoholic wine .... Here we can describe it as follows:
Wine A = Jiannanchun
Wine B = Wuliangye
Wine c = Alcoholic drink
...
What is manifested here is polymorphism. Jiannanchun, Wuliangye, alcoholic drinks are all the children of wine, we just through the wine a parent class can refer to different subclasses, which is polymorphism--we only know the specific instance object that the reference variable points to when we run it.
Admittedly, to understand polymorphism we have to understand what is "upward transition." In the inheritance we simply introduced the upward transformation, here in the long-winded: in the above drinking example, wine (Win) is the parent, Jiannanchun (JNC), Wuliangye (wly), alcoholic wine (JGJ) is a subclass. We define the following code:
JNC a = new JNC ();
For this code we are very easy to understand is simply to instantiate a Jiannanchun object. But that's it.
Wine a = new JNC ();
Here we understand that a wine type of a is defined here, which points to the Jnc object instance. Since Jnc is inherited and wine, Jnc can be automatically converted up to wine, so a can point to a Jnc instance object. There's a very big benefit in doing this, in inheritance we know that subclasses are extensions of the parent class that can provide more powerful functionality than the parent class, and that if we define a parent class reference type that points to a subclass, it can also use a subclass of powerful functionality, in addition to its ability to reference the common denominator of the parent class.
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 would be a little too---1 to exist only for methods and properties in subclasses.
public class Wine {public
void fun1 () {
System.out.println ("Wine fun ...");
Fun2 ();
}
public void Fun2 () {
System.out.println ("Wine Fun2 ...");
}
public class JNC extends wine{
/**
* @desc Subclass Overloaded Parent class Method * The method is not present in the parent class, and the parent class cannot refer to the method's
* @param a< c14/>* @return void
*/public
void Fun1 (String a) {
System.out.println ("JNC Fun1 ...");
Fun2 ();
}
/**
* Subclass Override Parent class method
* When referring to the parent class reference call Fun2, the method must be called/public
void Fun2 () {
System.out.println ("JNC Fun2 ... ");
}
public class Test {public
static void Main (string[] args) {
Wine a = new JNC ();
A.fun1 ();
}
-------------------------------------------------
Output:
Wine fun
... JNC's Fun2 ...
From the results of the program's operation, we find that a.fun1 () first runs the fun1 () in the parent class wine. Then run fun2 () in the subclass Jnc.
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).
For object-oriented, 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
2.1 Implementation Conditions
In the beginning it was mentioned that inheritance was being prepared for the implementation of polymorphism. Subclass Child inherits the parent class father, we can write a parent class type reference to a subclass that can handle either the parent class Father object or the child object, when the same message is sent to a subclass or parent class object. The object performs a different behavior based on the reference to which it belongs, which is polymorphism. That is, polymorphism is the same message that enables different classes to respond differently.
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.
2.2 Implementation Form
In Java, there are two forms of polymorphism that can be implemented. Inheritance and interfaces.
2.2.1, multi-state based on inheritance implementation
the implementation mechanism based on inheritance mainly manifests itself in the override of some methods by one or more subclasses of the parent class and inheriting the parent class, and multiple subclasses can perform different behaviors on the same method.
public class Wine {private String name;
Public String GetName () {return name;
public void SetName (String name) {this.name = name;
Public Wine () {} public String drink () {return "drink is" + getName ();
/** * Rewrite toString ()/Public String ToString () {return null;
} public class JNC extends wine{public JNC () {setname ("JNC");
/** * Overrides the parent class method to implement the polymorphic/public String drink () {return "drink is" + getName ();
/** * Rewrite toString () */public String toString () {return "Wine:" + getName ();
} public class Jgj extends wine{public jgj () {setname ("jgj");
/** * Overrides the parent class method to implement the polymorphic/public String drink () {return "drink is" + getName ();
/** * Rewrite toString () */public String toString () {return "Wine:" + getName (); }} public Class Test {public static void main (string[] args) {//Define parent class array wine[] wines = new Wine[2];
Defines two subclasses JNC JNC = new JNC ();
Jgj jgj = new jgj ();
The parent class references the subclass object Wines[0] = Jnc;
WINES[1] = jgj;
for (int i = 0; i < 2; i++) {System.out.println (wines[i].tostring () + "--" + wines[i].drink ());
} System.out.println ("-------------------------------"); } output:wine:jnc--Drink is JNC wine:jgj--drink is jgj-------------------------------
In the above code JNC, jgj inheritance wine, and rewrite the drink (), toString () method, the program runs the result is called the subclass of methods, output Jnc, jgj name, this is the expression of polymorphism. Different objects can perform the same behavior, but they all need to be implemented in their own way, which is thanks to the upward transformation.
We all know that all classes inherit from the superclass Object,tostring () method is also the method in object, when we write this:
Object o = new Jgj ();
System.out.println (O.tostring ());
The result of the output is wine:jgj.
Object, Wine, jgj three inheritance chain relationship is: Jgj->wine->object. So we can say this: When a subclass overrides a method of a parent class, only the most-end method in the object's inheritance chain is invoked. But note that if you write this:
Object o = new Wine ();
System.out.println (O.tostring ());
The result of the output should be null, because JGJ does not exist in the object inheritance chain.
So the polymorphism based on inheritance implementation can be summed up as follows: For a parent class type that refers to a subclass, when the reference is processed, it applies to all subclasses that inherit the parent class, the subclass objects differ, the methods are implemented differently, and the behavior of the same action is different.
If the parent class is an abstract class, then the subclass must implement all the abstract methods in the parent class, so that all subclasses of the parent class must have a uniform external interface, but their internal implementations can vary. This allows us to use the unified interface provided by the top-level class to handle the method at that level.
2.2.2, interface-based polymorphism
Inheritance is manifested by overriding several different subclasses of the same method of the parent class, which can be embodied by implementing the interface and overwriting several different classes of the same method in the interface.
In the polymorphism of an interface, a reference to an interface must be an instance program that specifies a class that implements the interface, and executes the corresponding method at run time based on the actual type of the object reference.
Inheritance is a single inheritance and can only provide a consistent service interface for a set of related classes. But interfaces can be multiple inheritance implementations that can be combined and augmented with a set of related or unrelated interfaces that provide a consistent service interface externally. So it's more flexible than inheritance. Third, the classic example.
Through the above, it can be said to have a certain understanding of polymorphism. Now strike the iron and see an example. This example is a classic example of polymorphism, excerpted from: Http://blog.csdn.net/thinkGhoster/archive/2008/04/19/2307001.aspx.
public class A {public String show (D-obj) {return ("A and D");
Public String Show (a obj) {return ("A and a");
} public class B extends a{public String show (b obj) {return ("B and B");
Public String Show (a obj) {return ("B and A"); } public class C extends b{} public class D extends b{} public class Test {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));
}
}
Run Result:
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
9- -A and D
Look at the results here 1, 2, 3 good understanding, starting from 4 began to be confused, for 4 why the output is not "B" and B.
First, let's look at a sentence: 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).
Analysis:
From the above program we can see that a, B, C, D are the following relationships.
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.
I can also confirm other answers in the same way.
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).
Author: chenssy
Source: http://www.cnblogs.com/chenssy/
This article copyright belongs to the author and blog Park, Welcome to reprint, but without the consent of the author must retain this paragraph, and in the article page obvious position to give the original connection, Otherwise, the right to pursue legal liability is retained.