Returning Values From Methods

It's often useful to have a method return a value to the class that called it. This is accomplished by the return keyword at the end of a method and by declaring the data type that is returned by the method at the beginning of the method.

For example, the following getLicensePlate() method returns the current value of the licensePlate field in the Car class.

 String getLicensePlate() {
    return this.licensePlate;
 }
 

A method like this that merely returns the value of an object's field or property is called a getter or accessor method.

The signature String getLicensePlate() indicates that getLicensePlate() returns a value of type String and takes no arguments. Inside the method the line

return this.licensePlate;

returns the String contained in the licensePlate field to whoever called this method. It is important that the type of value returned by the return statement match the type declared in the method signature. If it does not, the compiler will complain.


Previous | Next | Top | Cafe au Lait

Copyright 1997-8 Elliotte Rusty Harold
elharo@metalab.unc.edu
Last Modified October 16, 1998