Java Reference
In-Depth Information
When a method is invoked the caller must provide an argument of the
appropriate type for each of the parameters declared by the method. An
argument need not be exactly the same type as its corresponding para-
meter because some automatic conversions are applied. For example,
a byte argument can be converted to an int parameter, and wrapper
objects can be converted to their primitive values (and vice-versa) as
neededsee " Boxing Conversions " on page 198 .
Methods also have a return type, either a primitive type or a reference
type. If a method does not return any value, the place where a return
type would go is filled with a void .
The BodyPrint example illustrates a common situation in which you
would like to examine the state of an object. Rather than providing ac-
cess to all the fields of the object, a class can define a method that re-
turns a string representation of the state of the object. For example,
here is a method of the Body class to return a String that describes the
particular Body object it is invoked upon:
public String toString() {
String desc = idNum + " (" + name + ")";
if (orbits != null)
desc += " orbits " + orbits.toString();
return desc;
}
This method uses + and += to concatenate String objects. It first builds a
string that describes the identifier and name. If the body orbits anoth-
er body, we append the string that describes that body by invoking its
toString method. This recursion builds a string of bodies orbiting other
bodies until the chain ends with an object that doesn't orbit anything.
The resulting string is then returned to the caller by the return state-
ment.
The toString method of an object is specialit is invoked to get a String
when an object is used in a string concatenation expression using the +
operator. Consider these expressions:
 
Search WWH ::




Custom Search