4.8 Returning Objects

When your method returns one of the numeric types, it's pretty easy to determine whether a return instruction is legal. If the method descriptor ends with an I, indicating that an int is to be returned, then you must use the ireturn instruction, and the top of the stack must contain an int when the instruction executes. With objects, things are slightly tougher. The top of the stack must not only be a reference, but the object that it points to must be compatible with the return type of the method.

Suppose your method begins

 ; A method that returns a MountainBike .method public myRide ()LMountainBike; 

Because this method returns a reference, you must use an areturn instruction. This code is clearly illegal in this method:

 iconst_1 ireturn              ; Invalid: an int can't be a MountainBike 

The JVM verification algorithm checks that the object that is returned is an instance either of the class Bicycle or of some subclass of it. For example, this code is legal, because a DownhillMountainBike is a kind of MountainBike:

 new DownhillMountainBike       ; Create a DownhillMountainBike dup invokevirtual DownhillMountainBike/<init>()V areturn                        ; Return the DownhillMountainBike 

The null reference is special. It behaves as though it's an instance of every class, even though it's really an instance of no class at all. Therefore, this code is legal:

 aconst_null areturn            ; This is OK, since a null could be a Bicycle 


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