Java Reference
In-Depth Information
instancemethods.Theseclassmethodscanonlyaccessclassfieldsandcallclassmeth-
ods.
Passing Arguments to Methods
Amethodcallincludesalistof(zeroormore)argumentsbeingpassedtothemethod.
Javapassesargumentstomethodsviaastyleofargumentpassingcalled
pass-by-value
,
which the following example demonstrates:
Employee emp = new Employee("John ");
int recommendedAnnualSalaryIncrease = 1000;
printReport(emp, recommendAnnualSalaryIncrease);
printReport(new Employee("Cuifen"), 1500);
Pass-by-valuepassesthevalueofavariable(thereferencevaluestoredin
emp
orthe
1000valuestoredin
recommendedAnnualSalaryIncrease
,forexample)orthe
valueofsomeotherexpression(suchas
new Employee("Cuifen")
or
1500
)to
the method.
Becauseofpass-by-value,youcannotassignadifferent
Employee
object'sreferen-
ceto
emp
frominside
printReport()
viathe
printReport()
parameterforthis
argument. After all, you have only passed a copy of
emp
's value to the method.
Many methods (and constructors) require you to pass a fixed number of arguments
when they are called. However, Java also can pass a variable number of argu-
ments—such methods/constructors are often referred to as
varargs methods/construct-
ors
.Todeclareamethod(orconstructor)thattakesavariablenumberofarguments,spe-
cify three consecutive periods after the type name of the method's/constructor's right-
mostparameter.Thefollowingexamplepresentsa
sum()
methodthatacceptsavari-
able number of arguments:
double sum(double... values)
{
int total = 0;
for (int i = 0; i < values.length; i++)
total += values[i];
return total;
}
sum()
's implementation totals the number of arguments passed to this method;
for example,
sum(10.0, 20.0)
or
sum(30.0, 40.0, 50.0)
. (Behind the
scenes, these arguments are stored in a one-dimensional array, as evidenced by
val-