4.3 Constructors

Constructors in the Java virtual machine are methods named <init>. This is different from the Java language, which names constructors after the class being constructed. Each constructor must call the constructor of its base class somewhere in the method. Alternatively, you may call another constructor in the same class. A Java compiler enforces this rule by making you do a call to super or this as the very first thing in the constructor.

To call the base class constructor, you use the invokespecial instruction, just as you did to call the constructor. Here's an example of a constructor.

 .class MyClass .super MySuperClass ; A constructor taking no arguments .method <init>()V aload_0                                   ; Push this invokespecial MySuperClass/<init>()V      ; Call a superclass                                           ; constructor on this return                                    ; Return to the caller .end method 

MySuperClass must call its superclass constructor, and so on up to java/lang/Object.

The requirement that all classes must call a superclass constructor ensures that nobody can use a class without making proper initializations. This is crucial to the security of the JVM. Some methods depend on the class having been initialized before they can work safely.



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