Some simple understandings of polymorphism in Java

Source: Internet
Author: User

What is polymorphic1object-oriented three main 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. 2the definition of 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)3The technology for implementing polymorphism is called: Dynamic binding (Dynamicbinding), which refers to the actual type of the object being referenced during execution, and invokes its corresponding method according to its actual type. 4the role of polymorphism: to eliminate the coupling relationship between types. 5in 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 one, to have inheritance; second, to have the override; the parent class refers 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. 8.3is shown. 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. 2In a derived class, it is best to use a different name for the private method in the base class. 3The class that contains the abstract method is called an abstract class. 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. 4object Cleanup is in the reverse order of creation and, of course, if you want to manually clean up objects because you know the Java garbage collector. 5in the constructor method of the base class, the overridden method in the base class is called carefully, and the object initialization sequence is involved. 6the. Construction method is implicitly declared as a static method. 7Use 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, class polymorphism performance (1method overload overloading behaves as a method's polymorphism in the same class. A class of life multiple overloaded methods provide a variety of implementations for a function. At compile time, depending on the data type \ Number and order of the actual parameters of the method, decide which of the overloaded methods should be executed. (2subclass to redefine a member inherited from a parent class when a subclass inherits from a parent class does not fit the subclass. Subclasses cannot delete them, but can redefine them so that the members of the Frey adapt to the new requirements of the subclass. Subclasses redefine the parent class member, the member of the same name behaves polymorphism between the parent class and the child class, and the parent class object references the parent class member. Subclass objects refer to Subclass members without conflict and 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 override when the parameter list of a subclass method is identical to the parent method argument list (Override) Parent class method. 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 and not the value equality, a class overwrites the Equals () method of the object class, providing two objects of this class that compare the equality methods. Overrides are manifested by the polymorphism of the method between the parent class and the subclass. Java The principle of finding an execution method is to start with the class to which the object belongs, look for a matching method to execute, and, if there is no matching method in the current class, look 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 classSuper. Member Variables//Reference Parent-like member variable when child class hides parent class member variableSuper. Member method ([parameter list])//call the parent-like member method when the child class overrides the parent class member method*Note: Super references do not have a separate syntax3, there are two kinds of polymorphism:1compile-time polymorphism is called compile-time polymorphism for multiple methods with the same name, if at compile time it is possible to determine which of the same-name methods are executed.2Runtime polymorphism If it is not determined at compile time, it can only be determined at runtime to determine which of several methods of the same name is being 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 =NewXXXX (parameter list);//object obtains this class of instances, and the object is consistent with its referenced instance typeXXX xx1=NewXXX (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=NewXXX (parameter list);//the parent object obtains the subclass instance, and the subclass object is the parent class objectx2.tostring ();//run-time polymorphismX2 is declared as a parent class object but gets an instance of subclass XXX, then x2.tostring () actually executes the parent class method or the subclass override method.?This can be done in two cases, depending on whether the subclass overrides the parent class method. If the subclass overrides the parent class method, the subclass method is executed, and if there is no overwrite, the parent class method is executed. At compile time, the system cannot determine exactly which class should be executed based on the class the object belongs to, only the runtime can determine   So this is run-time polymorphic. The parent class object cannot execute all of the subclass methods, only those 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 do the following: forced: A method of implicitly doing type conversion.  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. A forced polymorphic forced polymorphism implicitly converts parameters into a type that the compiler considers correct to avoid errors. In the following expression, the compiler must decide the two-tuple operator '+' The work to be done: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=NewC ();D erived Derived=NewDerived (); 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 overloads allow the same operators or methods to represent distinct meanings. '+' There are two meanings in the above program: the number of the two double type is added, and the two strings are connected to each other. 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. Polymorphic polymorphic 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 Resource links) contains polymorphic behavior by the type of the value and the containing relationship of the collection. In many object-oriented languages, including Java, the inclusion relationship is a subclass

Parent class: Public Abstract classAnimal { Public Abstract voidSay ();} Sub-class: Public classDog extends Animal {@Override Public voidSay () {System. out. println ("Dog");}}  Public classCat extends animal{@Override Public voidSay () {System. out. println ("Cat");}} Parent class: Public classAnimal { Public voidSay () {};} Sub-class: Public classDog extends Animal { Public voidSay () {System. out. println ("Dog");}}

Some simple understandings of 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.