Java Virtual Machine Learning notes-method call and return (chapter 2)

Source: Internet
Author: User

19.1 method call

Java provides two basic methods: the instance method and the class (static) method. The difference between the two methods is:

1) An instance is required before the instance method is called, but the class method is not required.

2) The instance method uses dynamic binding, while the class method uses static binding.

When a Java Virtual Machine calls a class method, it selects the called Method Based on the type referenced by the object (usually known during compilation. On the contrary, when a virtual machine calls an instance method, it selects the called method based on the class of the object instance (only known at runtime.

The Java virtual machine uses two different commands to call these two methods respectively. For instance methods, use the invokevirtual command and the invokestatic command for class methods.

All call commands point to a constant pool entry that initially contains a symbolic reference. When the Java Virtual Machine encounters a call command, if there is no parsing symbol reference, the virtual machine uses the parsing symbol reference as part of the execution of the command invocation.

When the virtual machine processes the instance method, the objectref and ARGs (objectref is the this pointer implicitly passed to all instance methods) are displayed from the operand stack within the call method stack frame ). The Virtual Machine places objectref as the local variable 0 in the new stack frame (stack frame created for the called method), and uses all ARGs as the local variable 1, 2 ,... The VM uses the new stack frame as the current stack frame, and then points the program counter to the first instruction of the new method.

When a virtual machine is processing a method, the virtual machine only pops up parameters from the operand stack in the call method stack frame and places them into the new stack frame as the current stack frame, then point the program counter to the first instruction of the new method.

Supplement: The Virtual Machine generates a method table for each non-abstract class loaded and stores it as a part of the class information in the method area. A method table is an array of pointers to the method area. Its elements are directly referenced by all its instance methods, including the instance methods inherited from the superclass. Note that only non-private instance methods are available in the method table. Class methods called using the invokestatic command do not appear here because they are static and do not need to be indirectly pointed to in the method table, private methods and instance initialization methods do not need to appear here, because they are called by the invokespecial command, so they are also statically bound. When the Virtual Machine parses the symbolic reference method,

19.3 command invokespecial
The main difference between invokespecial and invokeirtual is that invokespcial usually (only one example) selects a method based on the referenced type rather than the class of the object. In other words, it uses static binding instead of dynamic binding. Dynamic binding does not produce the expected effect in the following three scenarios: invokespecial.
19.3.1 <init> () method
The <init> () method (or instance initialization method) is the place where the compiler places code for the constructor and instance variable initialization methods. Class provides a <init> () method for each constructor in the source file. If no constructor is declared in the source file, the compiler will generate a default constructor without parameters for this class. This default constructor usually ends with a <init> () method in the class file. Therefore, just as each class has at least one constructor, each class has at least one <init> () method, which is usually called using invokespecial.
The reason why invokespecial is used to call <init> () is that the <init> () method of the subclass must have the ability to call the <init> () method of the superclass. This reveals why multiple <init> () methods are called when an object is instantiated. The Virtual Machine calls the <init> () method declared in the object class. This <init> () method first calls other <init> () methods in the same class () method or the <init> () method in the superclass. This process runs through the lifecycle of the object.
For example, consider the following code:

class Dog{}class CockerSpaniel extends Dog{     public static void main(Stringargs[]){          CockerSpaniel bootsie = newCockerSpaniel();     }}

When the main () method is called, the virtual machine allocates space for the new cockerspanicl object, and then calls the default <init> () method of cockerspaniel to initialize the space. That method will first call the <init> () method of dog, and then call the <init> () method of the object again. The bytecode of the main () method of cockerspeni is as follows:

     //Create a new CockerSpaniel Object, push ref0 new #1 <Class CockerSpanial>     //Invoke <init>() method onobject ref     //new CockerSpaniel();3 invokespecial #3 <Method <init>() of class CockerSpaniel>    //Note compiler didn’t storeresulting ref in a var    //representing bootsia, because itwar neer used6 return   //return void from main

The main () method of the cockerspaniel class allocates memory for the new assumerspaniel object, use the new command to initialize the allocated memory to the default initialization value ("#1" refers to the constant entry of the class to be instantiated. Here it refers to the cockerspaniel class ). The new command pushes a reference pointing to the cockerspaniel object to the stack. Then the main () method uses the invokerspecial command to reference the <init> () method of the cockerspaniel class through this object ("#3" indicates the constant pool entry, this includes reference to the <init> () method of cockerspaniel ). The Java Virtual Machine pushes a new stack frame into the java stack, and then assigns the object reference to the local variable 0 in the new stack frame.
The bytecode of the <init> () method is as follows:

0 aload_0   //push object ref from localvar 1 Invoke Dog’s <init>() on object ref1 invokespecial $4 <Method <init>() of class Dog>4 return    //return void fromCockerSpaniel’s <init>()

As mentioned above, the <init> () method here is equivalent to the default no-argument constructor automatically generated by the compiler for the cockerspaniel class. This method first pushes the initialized object reference obtained from the local variable 0 to the stack. Then call the <init> () method of dog through this reference (#4 indicates the constant pool entry, which contains the reference of the <init> () method pointing to dog ). The bytecode of the <init> () method of the Dog class is as follows:

0 aload_0 //push obj ref from local var 0                 //invoke object’s <init>() method on obj ref1 invkespecial #3 <Method <init>()  of class java.lang.Object>0 return  //return void from Dog’s <init>()

The <init> () method is equivalent to the default no-argument constructor automatically generated by the compiler dog. This method is equivalent to the default construction method without parameters automatically generated by the compiler for the class dog. This method first extracts the reference of the initialized object from the local variable 0 and pushes it to the stack. Then, call the <init> () method of the object through this reference (#3 indicates the entry of the constant pool, which contains the reference to the <init> () method of the object. This constant pool does not point to the constant pool of the cockerspaniel method, and each class has its own constant pool ). After all three <init> () methods are returned. The cockerspaniel object created in main () is used to complete the initialization.
Because each class has at least one <init> () method. The <init> () method of the class has the same feature signature. (The feature signature of a method refers to its name, number and type of parameters ). For example, the cockerspaniel class inherits three <init> () methods from the path. Their feature signatures are the same. Cockerspaniel, dog, and object both have a no-argument method named <init>.
19.3.2 private Method
When processing a free instance method, you must allow the subclass to use a feature signature that is common to the super-class instance method to declare the instance method (invokespecial is only used to call the private instance method and cannot call the private class method, private class methods are called by the invokestatic command. For example, in the following code, interestingmethod () is a private method in the superclass. Subclass has the package access permission on it.

class Superclass{    private void interestingMethod(){    System.out.println("Superclass's interstingmethod.");    }    void exampleMethod(){    interestingMethod();    }}class Subclass extends Superclass{void interstingMethod(){System.out.println("Subclass's interesting method.");}public static void main(String args[]){Subclass me = new Subclass();me.exampleMethod();}}

As mentioned above. When you call the main () method in subclass as defined above, the virtual opportunity instantiate a new subclass object and then call the examplemethod () method. Main (the byte code of the 0 method is as follows:

//cerate a new instance of class subclass, push ref0 new #2 <Class Subclass>3 dup // Duplicate ref , push duplicate          //Invoke <init>()method on new object Subclass me = new SubClass();4 invokespacial #6 <Method <init>() of class Subcliass>7 astore_1  //pop object ref into local var 18 aload_1  // push re from local var 1                   //Invoke exampleMethod() on object ref;                    // me.exampleMethod();        9 invokeirtual #8 <method voidexampleMethod() of class Superclass>       12 return // return void from main()

Subclass inherits the examplemethod () method from the superclass. When the method main () calls the method examplemethod () in the subclass object. It uses the invokevirtual Command, as defined by the class superclass. The Java virtual machine creates a new stack frame and pushes it to the stack. Then, it executes the bytecode of examplemethod. The bytecode of the examplemethod () method is as follows:

0 aload_0 //push obj ref from local var 1                  //invoke interestingMethod() on obj ref               // interestingMethod()1 invokespecial #7 <method void interestingMethod() of Superclass>4 return // return void from exampleMethod()

Note that:Method examplemethod () The Prime Minister pushes the reference assigned to the local variable 0 to the stack (the implicit parameter TIMS is passed to all instance methods) and then calls interstingmethod through this reference using the invokespecial command. Although the object mentioned here is an instance of the subclass class and the interestingmethod () method in the subclass class can also be accessed, the Java Virtual Machine finally calls the interestingmethod () method in the superclas class.
The Java compiler translates the code into the invokespecial command when compiling the Java source code. When the Java Virtual Machine parses a symbolic reference pointing to the superclass in the invokespecial command. It dynamically searches for the current superclass. Find the implementation of this method in the nearest superclass. In most cases, the VM may find that the most recent method implementation exists in the superclass listed by symbolic references. However, virtual machines may also find the latest method implementation in another different superclass.
19.3.3 super keyword

When the super keyword is used to call a method (for example, super. somemethod (), although the method is reloaded by the current class. But what the user really wants to call is a superclass method. Once again, the invokevirual command can only call the methods of the current class. The superclass method cannot be used. For example:

class Cat{void someMethod(){}}class TabbyCat extends Cat{void someMethod(){super.someMethod();}}

The bytecode of the somemethod () method of tabbycat is as follows:

0 aload_0 // push obj ref from local var 0                  // invoke cat’s someMethod() on obj ref         1  invokespecial #4<method voiud someMethod() of class Cat>4 return // return void from TabbyCat’s someMethod()

If the invokevirtual command is used here, the somemethod () method of tabbycat will be called. However, the invokespecial command is used here. And the constant pool entry (#4 here) specifies the somemethod () method declared in the call class cat. Therefore, the Java Virtual Machine will call the super class somemethod ().

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.