(^82) | Java Syntax and Semantics, Classes, and Objects
As you might guess, the heading for a value-returning method omits the reserved word
void. In its place we write the name of a class or a primitive type. Here is an example of a head-
ing for a value-returning instance method calledfirstLastthat takes no parameters and re-
turns a string. Notice that the absence of thestaticmodifier makes it be an instance method.
publicString firstLast()// Public method; returns a string; has no parameters
There is one other difference between value-returning and void methods that appears
in the method body. We must indicate the value to be returned through the use of a return
statement. The syntax of the return statement is simple:
Let’s look at a complete value-returning method by finishing the definition of the instance
method firstLast. The following code assumes that the fields first,last, and middleare
string variables declared as instance fields in the enclosing Nameclass:
publicString firstLast() // Returns name in first-last format
{
returnfirst + “ “+ last;
}
Is that it? Yes, matters really are that simple. In fact, many value-returning methods are
equally as simple. They are often used as a way to provide a shorthand notation for a formula.
One characteristic of the object-oriented programming style is that we use many short meth-
ods as a means of building up a level of abstraction that simplifies the coding of larger prob-
lems. If we hide all of the details within classes and their methods, then the final solution
can be coded in a way that is simple and easy to understand, and thus easy to debug and
maintain. We call this kind of hiding encapsulation,and we discuss the underlying concepts
further in Chapter 4.
Now that we’ve seen how to write methods and classes, let’s go through the process of
building an object-oriented version of PrintName. We’ll do so in the context of a case study.
return expression ;
Return-Statement
やまだぃちぅ
(やまだぃちぅ)
#1