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 thereturn
statement to return the value. Any method declaredvoid
doesn't return a value. It may contain areturn
statement to break out of the method, but may not return a value. Any method that is not declaredvoid
must contain areturn
statement with a corresponding return value.Let's look at the
isEmpty
method in theStack
class: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() { return items.isEmpty(); }isEmpty
method isboolean
, and the implementation of the method returns the boolean valuetrue
orfalse
, depending on the outcome of the call toitems.isEmtpy
.The
isEmpty
method returns a primitive type. A method can return a reference type. For example,Stack
declares thepop
method that returns theObject
reference type:When a method uses a class name as its return type, such aspublic Object pop() { if (items.size() == 0) throw new EmptyStackException(); return items.remove(items.size() - 1); }pop
does, 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 whichImaginaryNumber
is 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 The class heirarchy for
ImaginaryNumber
Number
:Thepublic Number returnANumber() { ... }returnANumber
method can return anImaginaryNumber
but not anObject
.ImaginaryNumber
is aNumber
because it's a subclass ofNumber
. However, anObject
is not necessarily aNumber
it could be aString
or another type.You can override a method and define it to return a subclass of the original method, like this:
This technique, called covariant return type (introduced in release 5.0), means that the return type is allowed to vary in the same direction as the subclass. You can find another example of the covariant return type in the Annotations section.public ImaginaryNumber returnANumber() { ... }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.