10.15 Method Declarations

Here are two examples of method declarations:

 public abstract void function(); public static int add(int a, int b) {    return a+b; } 

Syntactically, field and method declarations are very similar. There are a few differences between a method declaration and a field declaration:

  • Different modifier keywords are used.

  • Following the method name is a list of arguments enclosed in parentheses. The parentheses are required; they are the key distinguishing syntax between field and method declarations.

  • Blocks of code are used instead of initializers. This block of code is required if the abstract keyword is not used.

To compile method declarations, the .method directive is used instead of .field. The method descriptor includes the argument types and the return type. Following the .method directive is a translation of the body of the method translated into bytecodes. The body may also contain .limit directives, which instruct the JVM how much memory to allocate for the method. The .method declaration is terminated with .end method.

The two example methods compile into

 .method public abstract function()V ; No method body, since the method is abstract .end method .method public static add(II)I .limit locals 2 .limit stack 2 iload_0 iload_1 iadd ireturn .end method 

Programming for the Java Virtual Machine
Programming for the Javaв„ў Virtual Machine
ISBN: 0201309726
EAN: 2147483647
Year: 1998
Pages: 158
Authors: Joshua Engel

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net