Java Reference
In-Depth Information
Car yourCar = new Car("Mazda", "RX-8", 2);
yourCar.printDetails();
}
}
Listing2-9 declaresaninstancemethodnamed printDetails() .Byconvention,
amethod'sname begins with alowercase letter,andthe first letter ofeach subsequent
word in a multiword method name is capitalized.
Methodsarelikeconstructorsinthattheyhaveparameterlists.Youpassargumentsto
theseparameterswhenyoucallthemethod.Because printDetails() doesnottake
arguments, its parameter list is empty.
Note Amethod'snameandthenumber,types,andorderofitsparametersareknown
as its signature .
When a method is invoked, the code within its body is executed. In the case of
printDetails() , this method's body executes a sequence of Sys-
tem.out.println() method calls to output the values of its make , model , and
numDoors instance fields.
Unlike constructors, methods are declared to have return types. A return type iden-
tifies the kind of values returned by the method (e.g., int count() returns 32-bit
integers). If a method does not return a value (and printDetails() does not), its
return type is replaced with keyword void , as in void printDetails() .
Note Constructors don't have return types because they cannot return values. If a
constructor could return an arbitrary value, how would that value be returned? After
all,the new operatorreturnsareferencetoanobject,andhowcould new alsoreturna
constructor value?
Amethodisinvokedbyusingthememberaccessoperator;theleftoperandspecifies
the object's reference and the right operand specifies the method to be called. For ex-
ample, the myCar.printDetails() and yourCar.printDetails() expres-
sions invoke the printDetails() instance method on the myCar and yourCar
objects.
Compile Listing 2-9 ( javac Car.java ) and run this application ( java Car ).
You should observe the following output, whose different instance field values prove
that printDetails() associates with an object:
Search WWH ::




Custom Search