Java Fundamentals-One of the four elements polymorphism

Source: Internet
Author: User

What is polymorphic

means that objects of different classes are allowed to respond to the same message. That is, the same message can be used in a variety of different ways depending on the sending object. (Sending a message is a function call)
Polymorphism refers to the specific type of reference variable defined in the program and the method call emitted by the reference variable is not determined during programming, but is determined during the program's run, that is, a reference to which the variable is inverted to the instance object of the class that the reference variable emits, and the method called by which class is implemented. Must be determined by the time the program is running. Because when the program is run to determine the specific class, so that, without modifying the source code, you can bind the reference variable to a variety of different class implementations, resulting in the invocation of the specific method of the reference change, that is, do not modify the program code can be changed when the program runs the specific code, so that the program can select multiple running state, This is polymorphism.
Polymorphism enhances the flexibility and extensibility of the software.

The technique of implementing polymorphism is called:

Dynamic binding, which refers to the actual type of the referenced object during execution, calls its corresponding method according to its actual type.

There are two types of polymorphism:

(1) Compile-time polymorphism: Dynamic reload at compile time, (2) Runtime polymorphism: Refers to an object can have more than one type, the override of the method is     divided into:     Understanding run-time polymorphism:     Car c = new Bus ();     Car compile-time type compile-time check whether the variable type exists and whether there is a method called. The     bus run-time type  is actually run to access the object in the heap, calling the actual method.     run-time polymorphism is the compile-time polymorphism determined by the run-time type, which is determined by the compile-time     type.

The role of polymorphism

Eliminates the coupling relationship between types.

Three necessary conditions for polymorphic existence

First, to have inheritance; second, to have a rewrite; the parent class refers to the child class object.

Benefits of Polymorphism:

1. Replaceable (substitutability).
Polymorphism is replaceable for existing code. For example, polymorphism works on the Circle Circle class and works on any other circular geometry, such as a ring. 2. Expandability (Extensibility).
Polymorphism has extensibility for code. Adding new subclasses does not affect the polymorphism, inheritance, and the operation and manipulation of other attributes of existing classes. In fact, new subclasses are more likely to get polymorphic functions. For example, it is easy to add the polymorphism of sphere class on the basis of realizing the multi-state of cone, semi-cone and hemispherical body. 3. Interface (interface-ability).
Polymorphism is a superclass that, by way of signature, provides a common interface to subclasses, which is implemented by subclasses to refine or overwrite the class. As shown in 8.3. The super-Class shape in the figure specifies two interface methods for implementing polymorphism, Computearea () and Computevolume (). Subclasses, such as circle and sphere, refine or overwrite both interface methods in order to achieve polymorphism. 4. Flexibility (flexibility).
It embodies the flexible operation in the application, and improves the use efficiency. 5. Simplification (simplicity).
Polymorphism simplifies the process of coding and modifying the application software, especially when dealing with the operation and operation of a large number of objects.

How to implement a polymorphic pattern:

Interface implementations, inheriting the parent class for method overrides, and method overloading in the same class.

eg

classA { PublicString Show (D obj) {return("A and D"); }             PublicString Show (A obj) {return("A and a"); }   }   classBextendsa{ PublicString Show (B obj) {return("B and B"); }            PublicString Show (A obj) {return("B and A"); }   }  classCextendsb{}classDextendsb{}

Perform

A A1 =NewA (); A A2=NewB (); b b=NewB (); C C=NewC (); D d=NewD (); System.out.println ("①:" +A1.show (b)); System.out.println ("②:" +A1.show (c)); System.out.println ("③:" +A1.show (d)); System.out.println ("④:" +A2.show (b)); System.out.println ("⑤:" +A2.show (c)); System.out.println ("⑥:" +A2.show (d)); System.out.println ("⑦:" +B.show (b)); System.out.println ("⑧:" +B.show (c)); System.out.println ("⑨:" +b.show (d));

Results

①:a and A②:a and A③:a and D④:b and A⑤:b and A⑥:a and D⑦:b and B⑧:b and B⑨:a and D

Analysis

①②③ better understand, generally will not be wrong. ④⑤ is a bit confused, why is not the output of "B and B" it?! Let's go back to polymorphism.

Runtime polymorphism is one of the most powerful mechanisms for object-oriented programming code reuse, and the concept of dynamic can also be said to be "one interface, multiple methods". Java's implementation of runtime polymorphism is based on dynamic method scheduling, which is a mechanism for calling overloaded methods at runtime rather than at compile time.

The overridden overriding and overloaded overloading of a method are different manifestations of Java polymorphism. Overriding overriding is a representation of polymorphism between a parent class and a subclass, and overloading overloading is a representation of polymorphism in a class. If you define a method in a subclass that has the same name and arguments as its parent class, we say that the method is overridden (overriding). When an object of a subclass uses this method, the definition in the subclass is called, and for it the definition in the parent class is "masked". If more than one method with the same name is defined in a class, they either have a different number of arguments or have different parameter types, which is called a method overload (overloading). The overloaded method is to change the type of the return value.

  when a Superclass object reference variable refers to 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. (However, if you force a superclass to be converted to subclasses, you can call methods that are newly added in the subclass and that are not available in the superclass.) )

Anyway In fact, this involves the priority of the method invocation, with the priority being high to Low: This.show (O), Super.show (O), This.show ((Super) O), Super.show ((Super) O). Let's take a look at how it works.

For example ④,a2.show (b), A2 is a reference variable, the type is a, then this is A2,b is an instance of B, so it went to class A to find show (b obj) method, not found, so to a super (superclass), and a no superclass, So go to the third priority This.show (Super) O, this is still A2, here O is B, (super) O that is (super) B is A, so it goes to class A to find the method of show (a obj), Class A has this method, But since A2 refers to an object of Class B, B overrides the show (a obj) method of a, so it eventually locks to show (a obj) of Class B, and the output is "B and A".

Another example is ⑧,b.show (c), B is a reference variable, type B, then this is B,c is an instance of C, so it to Class B to find Show (C obj) method, not found, instead of to the B's superclass a inside find, a inside also not, so also go to the third priority This.show ( (Super) O), this is B,o C, (super) o i.e. (super) C is B, so it finds the show (b-obj) method in B, found that because B refers to an object of Class B, it is directly locked to show (b obj) of Class B, and the output is "B and B".

According to the above method, the other results can be obtained correctly.

The question goes on, now let's see how the above analysis process reflects the meaning of the words in the blue font. It says that 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. Take A2.show (b) for a while.

A2 is a reference variable, type A, which refers to an object of B, so the meaning of this sentence is B to decide which method to invoke. Therefore, the show (b obj) of B should be called to output "B and B". But why is it inconsistent with the results from the previous analysis?! The problem is that we don't overlook the second half of the blue font, which is particularly important: the method that is called must be defined in the superclass, that is, the method covered by the quilt class. Does the show (b obj) inside B have a definition in super Class A? No! That's not to mention being covered. In fact, this statement hides a message: it is still determined by the priority of the method invocation. It finds show (a obj) in Class A, and if subclass B does not overwrite the show (a obj) method, then it calls the show (a obj) of a (because B inherits a, although it does not overwrite this method, but inherits this method from superclass a, in a sense, The method that is called is determined by B, except that the method is implemented in A); now subclass B overrides Show (a obj), so it eventually locks to show (a obj) of B. This is what the meaning of the sentence is.

Java Fundamentals-One of the four elements polymorphism

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.