On the significance and realization of the polymorphic mechanism

Source: Internet
Author: User

Million red envelopes, fiery open!!! Have you more wonderful!

I. Subtypes and subclasses

Here I want to first mention the difference between the word type (subtype) and the subclass (subclass), simply put, as long as the class A uses the extends keyword to implement the Class B inheritance, then we can say class A is a subclass of Class B, a subclass is a grammar-level word, and as long as the inherited syntax is satisfied, there is a subclass relationship.

Subtypes have stricter requirements than subclasses, which require not only inherited syntax, but also the requirement that if there is a child class overwrite (override) of the parent class method, the content of the rewrite must conform to the original semantics of the parent class, and its invocation should be consistent with the effect of the parent class implementation.

The contrast between the two is to emphasize one thing: only the guaranteed subclass is a subtype, polymorphism makes sense.

Ii. Mechanisms of polymorphism

There are essentially two types of polymorphism:

1, compile-time polymorphism (also known as static polymorphism)

2, run-time polymorphism (also known as dynamic polymorphism)

Overloading (overload) is an example of a compile-time polymorphism, where compile-time polymorphism is determined at compile time, and the runtime invokes a deterministic method when it runs.

What we usually call polymorphic refers to the runtime polymorphism, which is not sure at compile time which specific method to invoke, until the runtime can be determined. This is why sometimes polymorphic methods are called delay methods.

polymorphic behavior in Wikipedia is described as:

The primary usage of polymorphism in industry (object-oriented programming theory) is the ability of objects belonging To different types to respond to method, field, or property calls of the same name, each one according to an appropriate type-specific behavior.

The following is a brief introduction to the mechanism of run-time polymorphism (hereinafter referred to as polymorphism).

There are usually two implementations of polymorphism:

1. Subclass inherits Parent class (extends)

2. Class implementation interface (implements)

Either way, the core of this is the rewriting of the parent class method or the implementation of the interface method to achieve a different execution effect at run time.

To use polymorphism, you should follow a rule when declaring an object: The declaration is always the parent class type or interface type, and the actual type is created. For example, suppose we want to create a ArrayList object, and the declaration should take such a statement:

List=newArrayList();   

Instead of

ArrayList=newArrayList();   

the parent class type or interface type should always be preferred when defining method parameters , for example, a method should be written as:

Publicvoid dosomething(list list);     

Instead of

Publicvoid dosomething(ArrayList list);     

The greatest benefit of this statement is the flexibility of the structure: if one day I think that ArrayList's characteristics can not meet my requirements, I would like to be able to replace it with LinkedList, then only the object created in the place of the new ArrayList () will be changed to new LinkedList, no other code changes.

the programmer (and the program) does is not having to know the exact type of the object in advance, and so the exact Beha Vior is determined at Run-time (this is called late binding or dynamic binding).

The virtual machine dynamically invokes the actual class method when executing the program, which is automatically implemented by a mechanism called dynamic binding (also known as delayed binding), which is transparent to the programmer.

Iii. uses of polymorphism

Multi-State maximum use I think it's the reuse of design and architecture , and, more generally, the typical example of the use of polymorphism in design patterns , rather than programming for implementation, is advocated for interface programming. Define interfaces when defining features and components, and implementations can be left behind in the process. at the same time, an interface can have multiple implementations, and it can even be possible to use multiple implementations of an interface in a single design (for example, for ArrayList and LinkedList different features to determine which implementation to adopt).

Iv. realization of polymorphism

The following is a brief introduction to the implementation principle of polymorphism from the perspective of virtual machine runtime, which is an example of the implementation of Java virtual machines (java) and JVM specification.

When the JVM executes Java bytecode, type information is stored in the method area , usually in order to optimize the speed at which the object invokes the method, a pointer is added to the type information of the method area, which points to a table (called a method table) that records the entry of the class method. Each item in the table is a pointer to the appropriate method.

The method table is constructed as follows:

Because of the single-inheritance mechanism of Java, a class can inherit only one parent class, and all classes inherit from the object class. The method of the object class is first stored in the methods table, followed by the method of the parent class of the class, and finally the method of the class itself. The key point here is that if a subclass overrides a method of the parent class, the child class and the parent class share a method table entry that is considered a method of the parent class.

Note that only non-private instance methods are present, and static methods do not appear here, for reasons that are easy to understand: Static methods are independent of the object and can refer directly to the method address, rather than to an indirect reference as an instance method.

In more depth, static methods are called by the virtual machine Directive invokestatic, and private methods and constructors are called by the invokespecial directive. Only methods that are called by the invokevirtual and Invokeinterface directives appear in the method table.

Because of the arrangement of the above methods (object--parent class-subclass), the offset of the method table is always fixed . For example, for any class, the offset of the Equals method in its method table is always a fixed value, and the offset of the method defined by its parent class is always a fixed value for all method tables that inherit subclasses of a parent class.

As I said earlier, the table entries in the method table are pointers to the corresponding methods of the class, where the implementation of the polymorphic is started:

Assuming that class A is a subclass of Class B, and a overrides the method () of B, then in the method table of B, the method pointer points to the method entry of B.

For a, the method method in its methods table points to its own method instead of its parent class (which is guaranteed when the class loader loads the class, and the JVM guarantees that it will always be able to point to the correct type information from the object reference).

The combination of the method pointer offset is fixed and the pointer always points to the actual class of the Method field , and it is not difficult to find a polymorphic mechanism here:

When you call a method, you actually must first complete the symbolic reference resolution of the instance method, and the result is that the symbol reference is resolved to the offset of the method table. The virtual machine uses the object reference to get the entry of type information in the method area, queries the method table of the class, and when the subclass object is declared as a parent class type, the parent class method is called, at which point the virtual opportunity is from the method table of the actual class (although the parent class is declared, But in fact the type information here is stored in the subclass of information) to find the corresponding pointer to the method name ("Find" in this case is actually inappropriate, as mentioned earlier, the method's offset is fixed, so only by the offset to get the pointer), and then can point to the actual class method.

Our story is not over, in fact, the above process is only the use of inheritance to implement polymorphism of the internal mechanism, polymorphism of another way: the implementation of the interface is more complex, because thesingle inheritance of Java guarantees the linear relationship of the class, and the interface can be implemented more than one, So it is difficult to get the pointer of the method accurately by the offset. so in the JVM, there are actually two kinds of instructions for polymorphic instance method invocations:

The invokevirtual directive is used to invoke methods declared as classes;

the invokeinterface directive is used to invoke a method declared as an interface.

When using the invokeinterface instruction to invoke the method, it is not possible to use a fixed offset approach, only to honestly look for (of course, the actual implementation is not necessarily the case, the JVM specification does not specify how to implement such a lookup, Different JVM implementations can have different optimization algorithms to improve search efficiency. It is easy to see that, on the performance, the calling interface references a method that is often slower than the method that invokes the reference to the class. This also tells us that the preference of interfaces between classes and interfaces as design is not always correct, and of course design issues are not within the scope of this article, but it is clear that specific analysis of specific problems is still a better choice.

On the significance and realization of the polymorphic mechanism

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.