Classes and Interfaces (V) Java polymorphism, method rewriting, hiding

Source: Internet
Author: User
Tags instance method

First, the Java polymorphism

Object-oriented three major features: encapsulation, inheritance, polymorphism.

polymorphic types, divided into the following two kinds:

    • compile-time polymorphism: refers to a method overload . Compile-time polymorphism is at compile time to determine the call at the choice of the overloaded method, so also called static polymorphism, not really polymorphic. Therefore, the general state of polymorphism is run-time polymorphic.
    • run-time polymorphism: because of method overrides , you want to determine the entry of a method called by a reference variable, which must be determined based on the instance object that the reference variable at run time points to. This allows the same reference variable to invoke the same method, but different instance objects behave differently. Simply put, it is at run time that you can invoke a method in the implementation subclass by pointing to a pointer to the base class.

The following polymorphism refers to the polymorphic state at run time.

polymorphic definition: means that objects of different classes are allowed to respond differently 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);

The above definitions refer to the online version, and the different classes in the definition are extended by the same base class.

Benefits of Polymorphism:

    • Replaceable (substitutability). Polymorphism is replaceable for existing code. For example, the Draw function works on the Circle Circle class and works on any other circular geometry, such as a ring.
    • Extensibility (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.
    • 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.
    • Flexibility (flexibility). It embodies the flexible operation in the application, and improves the use efficiency.
    • 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.

Three elements of Java polymorphism:

    1. Inheritance
    2. Override
    3. A reference to a parent class that points to a reference to a subclass

The realization of polymorphism: rely on dynamic binding ;

Bind: Associates a method call with a method body.
Pre -binding: Binding before program execution, completed by compiler and linker, and C-language function call is pre-binding.
Dynamic binding: also called late binding . At run time, the method call binding is based on the specific object type. In addition static to methods, methods final (and private final methods), other methods are dynamically bound;

Second, method rewrite and hide

method Overrides: The method that inherits from the parent class is overridden in the subclass (not all parent-class methods can be overridden), allowing the overridden method to be invoked through a reference to the parent class. That is, the parent class type and the subclass type retain only the overridden method.

Hidden: overrides are relative overrides. When a subclass has the same method as the parent class, the overriding is that the subclass is only one copy of the parent class, but the method hides the subclass from the parent class, which is two copies. Among the members inherited from the parent class, except that some methods can be overridden, the remaining members are hidden, such as variables, inner classes, static methods, and so on.

Note: The final method can neither be overridden nor hidden.

classparentclass{ Public intA =5;protected FinalString name ="ParentClass"; Public Final void Finalmethod() {//final method, subclasses can neither rewrite nor hideSystem. out.println("Final Method"); } Public Static void Monday() {//static methodSystem. out.println("Monday () method for parent class ParentClass"); } Public void Count() {//inheritable Member methodsSystem. out.println("The Count () method of the parent class ParentClass"); }classinnerclass{//Inner class         Public Innerclass() {System. out.println("Inner class of parent class ParentClass"); }    }}classChildClassextendsparentclass{ Public intA =5;protected FinalString name ="ChildClass";/*//compilation does not pass* Public final void Finalmethod () {System.out.println ("final Method");    }*/         Public Static void Monday() {//static methodSystem. out.println("Subclass ChildClass Monday () method"); } Public void Count() {//inheritable Member methodsSystem. out.println("Count () method for subclass ChildClass"); }classinnerclass{//Inner class         Public Innerclass() {System. out.println("Inner class of subclass ChildClass"); }    }   } Public classMyTest { Public Static void Main(string[] args) {ChildClass Child =New ChildClass2(); ParentClass parent = child;//Type on turnSystem. out.println("hidden test-----------------for---------------variables"); Child.a=Ten; System. out.println("PARENT.A:"+parent.a); System. out.println("CHILD.A:"+child.a); System. out.println("\ n---------------The static method of the hidden test-----------------"); Parent.Monday(); Child.Monday(); System. out.println("\ nThe rewrite test for---------------method-----------------"); Parent.Count(); Child.Count(); System. out.println("\ n---------------hidden test-----------------for inner classes "); ParentClass.InnerclassPA = parent.New Innerclass(); ChildClass.InnerclassCH = child.New Innerclass(); }}

Hidden test for---------------variables-----------------
Parent.a:5
Child.a:10

---------------hidden test-----------------for static methods
Monday () method for parent class ParentClass
Monday () method for subclass ChildClass

Rewrite test for---------------method-----------------
The count () method of the subclass ChildClass
The count () method of the subclass ChildClass

---------------hidden test-----------------for inner classes
Inner class of parent class ParentClass
Inner class of subclass ChildClass

?? In the above example, only the count() method is overridden, the parent class type and the subclass type persist only the overridden method, while the other members are hidden, the parent class type remains one copy, and the subclass type remains one copy.

Criteria for method overrides
    • The overridden method is the instance method that the subclass inherits from the parent class and cannot be a static method
    • The return type of a subclass-overridden method must be a replaceable type of the return type of the original parent class method
    • The subclass overrides the access permission of the method to be less than the original parent class method;
    • The subclass cannot throw more exceptions than the parent class method.
    • When overriding a generic method, type erase occurs first. Then follow the 4 dots above, overriding the type erase method;

Replaceable type additions:

    • For return types that are basic type, void, the return type of the overridden method must be the same;
    • For a return type is a reference type, the return type can be substituted for the subtype of that type;
classparentclass{//Parent class         Public int Count() {//        return 0; } ObjectMethod() {return "AA"; } <textendsParentclass> TGetValue(T T) {//generic methodSystem. out.println();returnT }}classChildClassextendsparentclass{//Sub-class         Public int Count() {//Override Count () method, because the return type is basic type, cannot be changed, must be consistent        return 0; } PublicStringMethod() {//Override Method (): Access is increased, the return type is a subclass of object string        return "AA"; } ChildClassGetValue(ParentClass ch) {//Override generic Method GetValue ()        return NULL; }}

?? Parsing the generic method override in this example, after the generic method in the parent class getValue() is erased by type, is:

getValue(ParentClass t){    returnnull;}

Therefore, the method rewrite of the subclass ChildClass is reasonable.



Classes and Interfaces (V) Java polymorphism, method rewriting, hiding

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.