4.2 Creating Objects

Objects are created with the new instruction:

 new ClassName 

or

 new java/lang/Integer 

The class must not be marked abstract, and you must have permission to access it. If it's marked public, then you have permission. You also have permission if it isn't marked public but the class containing the new instruction is in the same package as the class being instantiated. When the new instruction is finished, there is a brand new uninitialized instance of the class on top of the stack.

You can't use the object until it has been initialized. To initialize the object, you must invoke one of the object's constructors. The constructor is always named <init>, and it always returns void. For example, there are two constructors for java/lang/Integer. Their descriptors are

 <init> (I)V <init> (Ljava/lang/String;)V 

The first of these initializes the Integer from an int; the other uses a String.

The call to the constructor wipes the reference to the object being constructed off the stack. Therefore, there's almost always a dup between the new instruction and the constructor invocation.

Constructors are invoked with invokespecial. In order to use invokespecial, the stack must contain the object you are initializing, followed by any arguments to the constructor. (We'll talk more about methods and arguments in section 4.5.) For example, to construct an Integer using the constructor that takes an int,

 new java/lang/Integer     ; Create the integer dup                       ; Make a copy of the reference to it bipush 27                 ; Push an argument                           ; Call the constructor invokespecial java/lang/Integer/<init> (I)V 


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

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