A few simple understandings of a Person's polymorphism in Java

Source: Internet
Author: User

What is polymorphic

    1. object-oriented three major features : encapsulation, inheritance, Polymorphism. From a certain point of view, encapsulation and inheritance are almost always prepared for POLYMORPHISM. This is our last concept, but also the most important point of knowledge.
    2. polymorphic definition : 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)
    3. the technique of implementing polymorphism is called Dynamic binding, which is the actual type of the referenced object that is judged during execution, and its corresponding method is called according to its actual type.
    4. the role of polymorphism: to eliminate the coupling relationship between Types.
    5. in reality, There are numerous examples of Polymorphism.

Here are the three necessary conditions for polymorphic existence, requiring you to recite them in a dream!

Three necessary conditions for polymorphic existence
first, to have inheritance;
second, to have a rewrite;
The parent class reference points to the subclass 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.


Implementation of polymorphism in Java: interface implementation, inheriting the parent class for method overrides, and method overloading in the same class.

1. In addition to the static and final methods in java, all other methods are bound at run Time. The private method is implicitly specified as final, so the final method is not bound at run Time. When you override a static, final, or private method in a base class in a derived class, you essentially create a new method.

2. In a derived class, it is best to use a different name for the private method in the base class.

3. Classes that contain abstract methods are called abstract Classes. Note that the definition contains this meaning, as long as the class contains an abstract method, the class is an abstract class. Abstract classes are derived from the role of the base class, providing a common interface for different subclasses.

4. The order of object cleanup is the opposite of the order of creation, of course, as long as you want to clean the object manually because you know the Java garbage collector.

5. Carefully call the overridden method in the base class in the constructor of the base class, where the object initialization sequence is Involved.

6. The construction method is implicitly declared as a static method.

7. Use the field to express changes in the state by using the difference between the inheritance expression Behavior.

There are two kinds of polymorphism in Java: runtime polymorphism and Compile-time Polymorphism.

A brief introduction to the polymorphism of classes is as Follows:

Polymorphism is one of the core features of object-oriented, and the polymorphism of class provides the flexibility of member design and the multiplicity of method execution in class.

1. Polymorphism of class performance

(1) Method Overloading

Overloading behaves as a method's polymorphism in the same class. a class of life multiple overloaded methods provide multiple implementations of a function. at compile time, depending on the data type \ Number and order of the Method's actual parameters, decide which of the overloaded methods should be Executed.

(2) subclasses redefine the members inherited from the parent class

Subclasses cannot delete a subclass when they inherit from a parent class, but can redefine them, allowing the Frey members to adapt to the new requirements of the SUBCLASS. subclasses redefine the parent class member, the member of the same name shows polymorphism between the parent class and the child class, the parent class object refers to the parent class member, the subclass object references the child class member, There is no conflict or Confusion.

Subclasses can redefine a member variable of the same name as the parent class, which is called a subclass to hide the parent class member Variable. subclasses can also redefine a member method of the same name as the parent class, which is called a subclass method overriding (override) the parent class method when the parameter list of the subclass method is identical to the parent class method parameter List. When overriding a parent class method, the access rights of the subclass method cannot be less than the permissions of the parent class Method.

Because the Equals () method of the object class compares the two object references for equality rather than the value equality, a class overwrites the Equals () method of the object class, providing two objects of this class comparing equality methods.

Overrides are manifested by the polymorphism of the method between the parent class and the Subclass. Java looks for methods of execution, starting with the class to which the object belongs, looking for a matching method to execute, or, if there is no matching method in the current class, looking up the matching method in the parent class or ancestor class, one by one, until the object class.

2. Super Reference

In a member method of a subclass, you can refer to a parent class member by using the pronoun super. the syntax for super references is as Follows:

Super ([parameter List])//in The constructor method body of the subclass, call the constructor of the parent class

Super. member Variables//when A subclass hides a parent class member variable, references a parent-like name member variable

Super. member Method ([parameter List])//when A subclass overrides a parent class member method, call the Parent-like member method

* Note: The Super reference does not use a separate syntax


3. There are two kinds of polymorphism:

1) Compile-time Polymorphism

For multiple methods with the same name, it is called Compile-time polymorphism if it is possible at compile time to determine which of the methods in the same name are Executed.

2) Run-time Polymorphism

If you are not sure at compile time, you can only determine at run time which of several methods with the same name is executed, which is called Run-time Polymorphism.


Method overrides exhibit two polymorphism, which is compile-time polymorphism when the object obtains this class instance, otherwise run-time polymorphism, for example:

XXXX x1 = new xxxx (parameter list); Object obtains this class of instances, and the object is consistent with its referenced instance type

xxx xx1 = new xxx (parameter list);

X1.tostring (); Compile-time polymorphism, The method of executing the XXX class.

Xx1.tostring (); Compile-time polymorphism, Execute the method of the XXXX class Coverage.

XXXX is the parent class of Xxx.

Because the subclass object is both a parent class object and a parent class object that has assignment compatibility with the subclass object, the parent object can be assigned a subclass Object. for example,

XXXX x2 = new XXX (parameter list); The parent object obtains the subclass instance, and the subclass object is the parent class object

X2.tostring (); Run-time polymorphism

X2 is declared as a parent class object but gets an instance of subclass xxx, then X2.tostring () does the parent class method or the subclass override method?

This is divided into two situations:

Depends on whether the subclass overrides the parent class Method. if the child class overrides the parent class method, the subclass method is executed;

If there is no overwrite, the parent class method is Executed.

At compile time, only the class to which the object belongs, the system cannot determine exactly how the class should be executed, only the runtime can determine it, so this is Run-time polymorphic.

The parent class object cannot execute all of the subclass methods, only the subclass methods that are overridden by the declaration \ Subclass in the parent class.

In such a system, polymorphism shows many forms of Ability. Generic polymorphic references have a large number of objects of the same structure type, and they share common characteristics. A specific polymorphism involves a small number of objects that do not have the same characteristics. Four polymorphic states can be described as Follows:

Mandatory: a method of implicitly doing type Conversions.

Overloaded: uses a marker as multiple meanings.

Parameter: provides the same action for different types of parameters.

Contains: The class contains abstract operations of the Relationship.

I'll give you a quick introduction to these polymorphic states before I tell you about subtype Polymorphism.

Forcing polymorphism

Forcing a polymorphic implicitly converts a parameter into a type that the compiler considers to be correct in a way that avoids errors. In the following expression, the compiler must determine what the two-tuple operator ' + ' should do:

2.0 + 2.0

2.0 + 2

2.0 + "2"

The first expression adds the operands of the two double, which is specifically stated in Java.

The second expression adds a double type and an int. This operation is not explicitly defined in Java. however, The compiler implicitly converts the second operand to a double type and adds the double type. It is very handy for programmers, or it will throw a compilation error or force the programmer to explicitly convert int to Double.

A third expression adds a double to a string. Such operations are also not defined in Java. so, The compiler converts a double into a string type and concatenates them.

Forcing polymorphism also occurs in a method Call. Suppose the class derived inherits the class Base, Class C has a method, the prototype is M (Base), and in the following code, the compiler implicitly converts the object derived of the derived class to the object of the Base class. This implicit conversion enables the M (Base) method to use all parameters that can be converted to the base class.

c C = new C ();

Derived Derived = new Derived ();

C.M (derived);

also, implicit casts can avoid the hassle of type conversions and reduce compilation Errors. of course, the compiler will still give precedence to validating object types that conform to the Definition.

Overloaded polymorphic

Overloading allows the use of the same operators or methods to represent distinct meanings. ' + ' in the above program has two meaning: two double type number added; two strings Connected. In addition, there are integral types, long integers, and so On. The overloads of these operators depend on the Compiler's choices based on the Context. The previous compiler implicitly converts the operand to a type that fully conforms to the Operator. Although Java explicitly supports overloading, user-defined operator overloads are not Supported.

Java supports user-defined function overloading. A class can have a method of the same name, and these methods can have different meanings. In these overloaded methods, the number of parameters must be satisfied, and the parameter types at the same location are Different. These differences can help the compiler distinguish between different versions of the Method.

The compiler represents different methods with this uniquely represented feature, which is more efficient than the name Representation. thus, all polymorphic behavior can be compiled and Passed.

Both forced and overloaded polymorphism are categorized as specific polymorphic, because these polymorphism are in a particular sense. These features, which are zoned into polymorphism, bring great convenience to Programmers. Forced polymorphism excludes troublesome types and compilation Errors. Overloaded polymorphic like a piece of sugar that allows programmers to represent different methods with the same name is Convenient.

Polymorphism of parameters

Parameter polymorphism allows many types to be abstracted into a single representation. For example, in the list abstract class, a set of objects with the same characteristics is described, providing a common Template. You can reuse this abstract class by specifying a Type. These parameters can be any user-defined type, and a large number of users can use this abstract class, so parameter polymorphism is undoubtedly the most powerful polymorphic.

At first glance, the above abstract class seems to be a function of Java.util.List. however, Java does not actually support true security Type-style parameter polymorphism, which is why other collection classes of Java.util.List and Java.util are written with the original Java.lang.Object (refer to my article "A primordial Interface? "for More details). The Single-root inheritance of Java solves some problems, but does not play the full function of the parameter Polymorphism. Eric Allen has a wonderful article "behold the Power of parametric polymorphism", which describes the Java generic types of requirements and recommends to Sun's Java specification requirements #000014 document "ADD Generic Types to the Java programming Language. " (refer to Resources Link)

The included polymorphic

A polymorphic behavior is implemented by a type that contains polymorphic values and the inclusion relationship of a collection. in many object-oriented languages, including java, the inclusion relationship is a subtype. therefore, Java's Inclusion polymorphism is a subtype of polymorphism.

A few simple understandings of a Person's polymorphism in Java

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.