In-depth understanding of Java polymorphism mechanisms

Source: Internet
Author: User

From the bytecode level, all the method calls in Java end up being converted to the following invocation directives.

    • invokestatic: Calls a static method.
    • invokespecial: invokes instance constructors <init> methods, private methods, and parent class methods.
    • invokevirtual: All virtual methods are called.
    • invokeinterface: Invokes an interface method that, at run time, determines an object that implements this interface.
    • invokedynamic: Call the dynamic method. JDK 7 was introduced primarily to support method invocation of dynamic languages.

The JVM provides the above 5 method invocation instructions, so it is advisable to take a peek at the execution of the Java polymorphic mechanism from the bytecode level.

1 virtual methods and non-virtual methods

The invokevirtual in the 5 method invocation directives above are responsible for invoking all virtual methods. So what is a virtual method? What is a non-virtual method?

From the Java language level,static,private,final-decorated methods, parent-class methods, and instance constructors are called non-virtual methods. In contrast, all other methods are called virtual methods.

At the byte-code directive level, the methods called by Invokestatic and Invokespecial are non-virtual methods.

2 static types and actual types

Let's take a look at the definition of the following code:

New Man ();

We refer to human as the static type of the variable, and man is called the actual type of the variable.

A reference variable has two types: a static type (which defines the type of the variable) and the actual type (the type of the object that actually points to).

Static types are known at compile time, and actual types are determined only by the runtime.

3 implementation of polymorphic mechanisms in Java

The run-time parsing process of the Invokevirtual directive is broadly divided into the following steps:

    1. Finds the actual type of the object pointed to by the first element at the top of the operand stack, and is recorded as C
    2. If you find a method in type C that matches the descriptor in the constant and the simple name, the access check is performed, and if passed returns a direct reference to the method, the lookup process ends, and if it does not, the Java.lang.IllegalAccessError exception is returned.
    3. Otherwise, follow the inheritance relationship from the bottom up to the next step in the search and validation process for each of the parent classes in C . 2.
    4. If the appropriate method is never found, the Java.lang.AbstractMethodError exception is thrown.

It is precisely because the invokevirtual directive is such an execution process that it explains why the implementation of polymorphism in the Java language requires the following three conditions:A. The parent class reference points to the subclass object. B. There is a succession of existence. C. Subclasses override parent class methods.

    • Because the parent class reference points to the subclass object, the JVM will go first to find the type corresponding to the subclass object.
    • And because of the existence of inheritance, so the subclass of the method can not be less than the parent class, which guarantees that, as long as the reference variable can call the method, the subclass must exist. So the second step must be able to find the called method in the subclass's type.
    • When the method is found, it can be executed, and if the method does not produce different effects (polymorphic), it depends on whether the subclass overrides this method. So to create polymorphism, subclasses have to rewrite the parent class method. Note: The methods described above refer to virtual methods. 】

4 static allocation and dynamic dispatch

The dispatch process reveals some of the most basic patterns of polymorphism, such as how "Overrides" and "overloads" are implemented in a Java virtual machine.

4.1 Static allocation

The dispatch action of all dependent (argument) static types to locate the execution version of the method is called a static dispatch. A typical application is method overloading (overload).

Let's look at an example:

PublicClassStaticdispatch {StaticClassHuman {}StaticClass MansExtendsHuman {}StaticClass womenExtendsHuman {}PublicvoidSayHello (Human guy) {System.out.println ("Hello, guy!"); }public void SayHello ( Man Guy) {System.out.println ("Hello, man!" ); } public void SayHello ( Women guy) {System.out.println ("Hello, women!" ); } public static void< Span style= "color: #000000;" > main (string[] args) {Human man = new man (); Human women = new women (); Staticdispatch sd = new Staticdispatch (); Sd.sayhello ( Man); Sd.sayhello (women); }} 

Output Result:

Hello, guy!.
Hello, guy!.

Yes, the program is a familiar overload (overload). In the above procedure, because the recipient of the method has determined that the Staticdispatch is an instance of SD, the final call to which overloaded version depends on the type of the incoming parameter.

The nature of overloading in Java

When the compiler is overloaded, it is based on the static type of the passed-in argument instead of the actual type. Static types are known at compile time, so during the compile phase, the compiler invokes that overloaded version based on the static type of the argument.

4.2 Dynamic allocation

The dispatch fault of the method execution version is called dynamic Dispatch at run time based on the actual type of the variable. A typical application is rewriting (override). Examples are as follows:

 Public classDynamicdispatch { Public Static voidMain (string[] args) {Human man=NewMan (); Human Women=Newwomen ();        Man.sayhello ();                 Women.sayhello (); Mans=Newwomen ();     Man.sayhello (); } } Abstract classHuman {protected Abstract voidSayHello ();} classMansextendsHuman {@Overrideprotected voidSayHello () {System.out.println ("Hello man!"); }     } classWomenextendsHuman {@Overrideprotected voidSayHello () {System.out.println ("Hello women!"); }     }

Output Result:

Hello man!
Hello women!
Hello women!

The nature of rewriting in Java

See the parsing process at runtime of the invokevirtual directive.

4.3 General examples
PublicClassDispatch {StaticClassqq{}StaticClass_360{}PublicStaticClassfather{PublicvoidHardchoice (_360 _360) {System.out.println ("Father Choose 360")); }PublicvoidHardchoice (QQ QQ) {System.out.println ("Father choose QQ")); } }PublicStaticClass SonExtendsfather{PublicvoidHardchoice (_360 _360) {System.out.println ("Son Choose 360"); } public void Hardchoice (QQ QQ) {System.out.println ("Son choose QQ");} public static void main (string[] args) {Father Father = new Father (); Father son = new son (); Father.hardchoice (new _360 ()); Son.hardchoice (new QQ ());}}             

Output Result:

Father Choose 360
Son Choose QQ

The analysis is as follows:

New Father ();        new Son ();                /*** /Father.hardchoice (new/** */ son.hardchoice (new QQ ());    

5 Virtual machine dynamic Dispatch implementation
  • because dynamic dispatch is a very frequent operation, based on performance considerations, in < Span lang= "en-US" >JVM virtual for classes in the method area. Method Table also known as vtable ). Corresponding to this, invokeinterface itable ).
  • The virtual method table holds the actual entry address of each method. If a method is not overridden in a subclass, then the address entry for the virtual method table of the subclass is consistent with the address entry for the same method as the parent class. If the subclass overrides this method, the address in the Subclass method table is replaced with the entry address that points to the subclass implementation version.

Resources

http://blog.csdn.net/kobejayandy/article/details/39620679

Http://www.cnblogs.com/jack204/archive/2012/10/29/2745150.html

http://blog.csdn.net/oypc2303/article/details/4393831

http://blog.csdn.net/lidaweihgy/article/details/7660346

Http://www.cnblogs.com/qinqinmeiren/archive/2011/07/15/2151687.html

Http://www.geekcome.com/content-10-4128-1.html


In-depth understanding of Java polymorphism mechanisms

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.