Deep understanding of a series of JAVA polymorphic mechanisms (overload/rewrite) __java

Source: Internet
Author: User
Tags instance method

Polymorphism (polymorphism) literally means "multiple states." In object-oriented language, many different implementations of interfaces are polymorphic (from Baidu Encyclopedia). Therefore, in fact, according to this meaning polymorphic "theme" is the object, but actually in our application we often call "overload" and "rewrite" called "polymorphism" in fact, this is not rigorous. Overloading and rewriting are just two types of application representations of polymorphism, which means that we see the "power" of polymorphism precisely because of overloading and rewriting. So when we talk about the polymorphism implementation mechanism, we are talking about the implementation mechanism of overloading and rewriting. question one, what is the advantage of polymorphism.

Polymorphism is the implementation of interface-oriented programming, and interface programming can reduce the coupling between the code, so it is more abstract we still use an example to illustrate:

Package Duotai;

Public interface Living_beings {public
  void run ();
}


Class Human implements living_beings{
  @Override public
  void Run () {
    System.out.println ("Human running");

The class Dog implements living_beings{
  @Override public
  void Run () {
    System.out.println (" Dog running ");
  }
}
Package Duotai;

public class Main {public

  void call (Living_beings living_beings) {
    living_beings.run ();
  }

  public static void Main (string[] args) {
    new Main (). Call (New Human ());
    New Main (). Call (New Dog ());
  }

Output:
Human Running
Dog Running

This is interface-oriented programming, which means that when I apply a class (the call method is applying a class) it is not directly oriented to this class but to the interface--that is, by passing the interface variable, an interface can correspond to different "states" because of the Java polymorphism. So I can use a "state" in the next dynamic (such as using human in the Main method) and dynamically add this "state" (if there is a new "creature" added like cat, then the direct implementation of living_being does not need to change the call method, Because the interface is oriented so long as the interface needs constant call method does not need to change, and this is the embodiment of "rewrite" .

For overloading , the same method name is allowed to have a different method signature, so that when the method is invoked, the function we need is invoked based on the difference in the method signature. We can "overload" in the same class, of course, you can also "overload" the methods of the parent class-the difference between overloading and overriding the parent class method is that the override is equivalent to overriding the parent class, which in addition to inheriting the method of the parent class is equivalent to adding a function. Overloading makes it easier for code to distinguish the features of the same method to achieve different functions. But note that when overloading encounters polymorphism, we need to analyze it carefully:

Package Duotai;

public class Main {public

  void call (Living_beings living_beings) {
    living_beings.run ();
  }

  public void Run (living_beings living_beings) {
    System.out.println (???? running);
  }

  public void Run (Human Human) {
    System.out.println (' Now Human is running ');
  }

  public void Run (Dog Dog) {
    System.out.println (' Now Dog is running ');
  }

  public static void Main (string[] args) {
    living_beings human = new Human ();
    Living_beings dog = new Dog ();
    New Main (). Run (human);
    New Main (). Run (dog);
  }
}

Run Result:
Now all is running
Now all is running

Here the Run method is overloaded (passing in different parameter types), but when actually used, although the actual types are human and dog, the method invocation is actually called living_being. Here you have to explore the problem of how overloading and rewriting of the "polymorphic" attribute can be implemented in the JVM. problem Two, polymorphism in the JVM virtual machine implementation mechanism is what.

We see that for the override method run (), the method call (Living_being.run ()) determines the final method invocation based on the actual type of the object (that is, the new type), but the method overload determines which method overload is selected based on the type of declaration. This is because of the static dispatch and dynamic dispatch in the JVM involved.

Before explaining the static dispatch and dynamic dispatch, let's talk about the concept of "method invocation" first.
method call is to solve the problem of how to choose the correct target method, which is divided into " parse call" and "dispatch call". The information for each method in the JVM is actually in the constant pool of the class file in the form of a constant, and the parsing phase of the class load resolves the method information and loads it correctly into the target method and executes, some of which are fully written into the class file. Only from the class file information can be resolved, this method call is called "parsing", that is, parsing must be a static process, in the compilation can be fully determined during the class loading phase can be directly related to the method of the symbolic reference to the direct reference can be determined. But attention to dispatch is both static and dynamic, and static concepts and parsing are similar. Dynamic refers to the fact that the compilation period does determine a symbolic reference at compile time, but the true direct reference is not determined until it is run. So there are several instructions for parsing and assigning:

Invokestatic: Calling a static method.
Invokespecial: Invokes the Instance builder method, Private method, and parent class method.

Invokevirtual: All virtual methods are invoked.
Invokeinterface: Calls an interface method, and then determines an object that implements this interface at run time.
invokedynamic: Dynamically resolves the method referenced by the call-point qualifier at run time, and then executes the method before the 4 invocation instruction, which is solidified within the Java Virtual machine, The dispatch logic of the invokedynamic instruction is determined by the guidance method set by the user.

The first two of these can be identified in the parsing phase, which we call "non-virtual methods," such as static methods, private methods, instance constructors, and parent-class methods. Instead, other methods are called "virtual methods." Here we are talking about the virtual method.

for static allocations , we define all dispatch actions that depend on the execution version of the static type of positioning method, and the typical application is the overload mentioned above: static dispatch occurs at compile time, and Javac determines which version to use based on the static type when compiling. And the notation of this method is written to the parameters of the two invokevirtual instruction of the main method.
for dynamic dispatch , it can actually be divided into interface method dispatch, inheritance method assignment. The JVM virtual machine generates a method table for the current related class (its own class, interface, parent class, subclass) before the method is dispatched, and the method assigned to the inherited parent class:
The JVM first looks at the method table in which the constant pool declares the parent class parents, and it gets the offset of the method's offsets in the methods table, which is the direct reference to the method invocation. When a direct reference to a method call is resolved (method table offset offsets), the JVM performs a true method call: The argument to the instance method calls this gets the concrete object (that is, the object in the heap that the inherited object child points to), and thus gets the corresponding method table for the object. In turn, call the method that an offset in the method table points to.

For interface method calls, the implementation is simpler:
The JVM first looks at the constant pool, determines the symbolic reference (name, return value, and so on) of the method call, and then uses the instance pointed to to get the method table for the instance, and then searches the method table to find the appropriate method address. Because each interface call is searched for a method table, the invocation of the interface method is, in efficiency, always slower than the invocation of the class method, and we understand the process by recompiling the "rewrite" example into a bytecode instruction:
Source code:

public static void Main (string[] args) {
 living_beings human = new Human ();
    Living_beings dog = new Dog ();
    Human.run ();
    Dog.run ();
  }

Reverse Compile:

public static void Main (java.lang.string[]);
    Code:
       0:new           #8                  //class Duotai/human
       3:dup
       4:invokespecial #9                  //Method Duotai/human. " <init>:() V
       7:astore_1
       8:new           #10                 //class Duotai/dog
      11:dup
      12:invokespecial #11                 //Method Duotai/dog. " <init> ":() V
      15:astore_2
      16:aload_1
      17:invokeinterface #2,  1            //Interfacemethod Duotai/living_beings.run: () V
      22:aload_2
      23:invokeinterface #2,  1            //Interfacemethod duotai/ Living_beings.run: () V
      28:return
}

If you want to know more detailed method table information, please refer to the
Java Multi-State implementation principle

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.