Java Virtual Machine-the implementation mechanism of polymorphism

Source: Internet
Author: User

"Deep Java Virtual machine" V: Polymorphism Implementation Mechanism--static dispatch and dynamic dispatch

Method parsing

The process of compiling a class file does not include a connection step in a traditional compilation, and all method calls store only symbolic references in the class file, not the entry address of the method in the memory layout when it is actually run. This feature gives Java a much more dynamic ability to expand dynamically, making it possible to determine the direct references to certain target methods during the class run, called Dynamic joins, and the symbolic references of some methods to direct references during the class loading phase or first use, which is called static parsing. This is mentioned in the previous article, "Java memory area and memory overflow".

Static parsing is based on the premise that the method has a deterministic version of the call before the program is actually executed, and that the invocation version of the method is immutable at run time. In other words, the invocation target must be determined when the compiler compiles, and the invocation of such a method is called parsing.

In the Java language, the method conforming to the "compiler know that the runtime is immutable" is mainly a static method and a private method of two categories, the former is directly associated with the type, the latter is not accessible externally, neither of these methods can be inherited or other ways to rewrite the other version, Therefore, they are suitable for parsing during the class loading phase.

A total of four method invocation byte instructions are provided in the Java Virtual machine, respectively:

    • 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.
As long as the method can be called by the invokestatic and invokespecial instructions, you can determine the unique invocation version in the parsing phase, there are static methods, private methods, instance constructors, and parent class methods that conform to this condition. They resolve the symbolic reference to a direct reference to the method when the class loads. These methods can be called non-virtual methods (also including the final method), and in contrast, other methods are called virtual methods (except the final method). In particular, the final method is described here, although the call to the final method uses the Invokevirtual directive, but because it cannot be overwritten, there is no other version, so there is no need for the recipient to make polymorphic selections.    The Java language specification explicitly illustrates that the final method is a non-virtual method. The parse call must be a static process, fully deterministic during compilation, and the referenced symbolic reference is converted to a deterministic direct reference during the parsing phase of the class load, and will not be deferred until the run time. The dispatch call may be static or dynamic, and it can be divided into single and multiple allocations based on the number of parcels on which the method is assigned (the caller and the method's parameters are collectively referred to as the method's volume).    The combination of the two types of dispatch mode 22 is composed of static single dispatch, static multi-Dispatch, Dynamic single dispatch, dynamic multi-Dispatch and four kinds of dispatch. Static Dispatch

All dispatch actions that rely on static types to locate methods to perform versions are called static allocations, and the most typical application of static dispatch is the method overloads in polymorphism. Static dispatch occurs during the compilation phase, so determining that statically assigned actions are not actually performed by the virtual machine. The following is an example of a method overload that illustrates this dispatch mechanism more clearly:

[Java]View PlainCopy
  1. Class human{
  2. }
  3. Class man extends human{
  4. }
  5. Class Woman extends human{
  6. }
  7. Public class staticpai{
  8. public void Say (Human hum) {
  9. System.out.println ("I am Human");
  10. }
  11. public Void Say (Mans hum) {
  12. System.out.println ("I am Man");
  13. }
  14. public void Say (Woman hum) {
  15. System.out.println ("I am Woman");
  16. }
  17. public static void Main (string[] args) {
  18. Human mans = New Man ();
  19. Human woman = New Woman ();
  20. Staticpai sp = new Staticpai ();
  21. Sp.say (man);
  22. Sp.say (woman);
  23. }
  24. }
The above code executes the following results:

I am Human
I am Human

The above results should not be difficult to analyze. Before analyzing why an overloaded method with the parameter type human is chosen to execute, look at the following code:

Human mans = New Man (); We call the "Human" in the above code the static type of the variable, and the following "man" is called the actual type of the variable.    static types and actual types can change in the program, except that static type changes occur only when they are used, that the static type of the variable itself is not changed, and that the final static type is known at compile time, and the result of the actual type change is determined at run time. Back in the code analysis above, when calling the Say () method, the caller of the method (recalling the definition of the volume above, the caller of the method is a number of parcels) is an SP, and the overloaded version that is used depends entirely on the number of incoming parameters and the data type (the parameter of the method is also the data volume). The code deliberately defines two variables with the same static type and different actual types, visibleThe compiler (not a virtual machine) is determined by the static type of the parameter and not the actual type, if it is judged by the static type, at compile time. And the static type is the compile period, so during the compilation phase, the Javac compiler determines which overloaded version to use based on the static type of the parameter. This is the most typical application for static dispatch.

Dynamic dispatch dynamic dispatch and the other important manifestation of polymorphism-method overwrite have very close relation. The method of calling subclass overwrite after upward transformation is a good example of dynamic dispatch. This is a common situation, so it is no longer analyzed with the sample program. Obviously, when judging the method that executes the parent class or the method covered in the subclass, if the static type is used to judge, then the method in the parent class is only called, regardless of how it is transformed, but the reality is that, depending on the subclass that is instantiated by the parent class, the calling method is overridden in different subclasses, it is clear that This is to dispatch the execution version of the method based on the actual type of the variable. The actual type determination needs to be determined when the program is run, which is called dynamic Dispatch in the run time based on the actual type determination method execution version of the dispatch process.

Single Dispatch and multiple dispatch

Previously given: The method's recipient (that is, the method's caller) and the method's parameters are collectively referred to as the method's volume. However, an assignment is a selection of the target method based on one volume, and the multiple allocation selects the target method based on more than one volume.

For ease of understanding, here is a sample code:[Java]View PlainCopy
  1. Class eat{
  2. }
  3. Class drink{
  4. }
  5. Class father{
  6. public void dosomething (Eat arg) {
  7. System.out.println ("Dad is eating");
  8. }
  9. public void dosomething (Drink arg) {
  10. System.out.println ("Daddy is Drinking");
  11. }
  12. }
  13. Class child extends father{
  14. public void dosomething (Eat arg) {
  15. System.out.println ("The Son is eating");
  16. }
  17. public void dosomething (Drink arg) {
  18. System.out.println ("The Son is Drinking water");
  19. }
  20. }
  21. Public class singledoublepai{
  22. public static void Main (string[] args) {
  23. Father Father = new Father ();
  24. Father child = new Child ();
  25. Father.dosomething (new Eat ());
  26. Child.dosomething (new Drink ());
  27. }
  28. }
The results of the operation should be easily predicted, as follows: Dad's eating.
Son's drinking.
We first look at the compiler's selection process, the static dispatch process, during the compile phase. There are two points for choosing a target method: First, whether the static type of the method's recipient (that is, the caller) is father or child, and the second is whether the method parameter type is eat or drink. Because the selection is based on two parcels, the static assignment of the Java language is a multi-dispatch type.
Then look at the selection of the virtual machines in the run phase, the dynamic dispatch process. Since the compile time has determined the parameter type of the target method (the compilation period is statically dispatched based on the static type of the parameter), the only factor that can affect the selection of the virtual machine is the actual type of the recipient of this method is father or child.          Because only one of the parcels is selected, the dynamic dispatch of the Java language belongs to the single-dispatch type. According to the above argument, we can summarize as follows: The current Java language (JDK1.6) is a static multi-dispatch, dynamic single-Dispatch language.

Java Virtual Machine-the implementation mechanism of polymorphism

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.