|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
You declare a method's return type in its method declaration. Within the body of the method, you use thereturnstatement to return the value. Any method declaredvoiddoesn't return a value and cannot contain areturnstatement. Any method that is not declaredvoidmust contain areturnstatement.Let's look at the
isEmptymethod in theStackclass:The data type of the return value must match the method's declared return type; you can't return an integer value from a method declared to return a boolean. The declared return type for thepublic boolean isEmpty() { if (items.size() == 0) { return true; } else { return false; } }isEmptymethod isboolean, and the implementation of the method returns the boolean valuetrueorfalse, depending on the outcome of a test.The
isEmptymethod returns a primitive type. A method can return a reference type. For example,Stackdeclares thepopmethod that returns theObjectreference type:When a method uses a class name as its return type, such aspublic Object pop() { if (top == 0) { throw new EmptyStackException(); } Object obj = items[--top]; items[top]=null; return obj; }popdoes, the class of the type of the returned object must be either a subclass of or the exact class of the return type. Suppose that you have a class hierarchy in whichImaginaryNumberis a subclass ofjava.lang.Number, which is in turn a subclass ofObject, as illustrated in the following figure.Now suppose that you have a method declared to return a Number:Thepublic Number returnANumber() { ... }returnANumbermethod can return anImaginaryNumberbut not anObject.ImaginaryNumberis aNumberbecause it's a subclass ofNumber. However, anObjectis not necessarily aNumber it could be aStringor another type.You also can use interface names as return types. In this case, the object returned must implement the specified interface.
|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.