Java Reference
In-Depth Information
enough information to choose which method to call when it encounters
sum(1.0,
2.0)
in source code.
Reviewing Method-Invocation Rules
The previous examples of method invocation may seem confusing because you can
sometimes specify the method's name directly, whereas you need to prefix a method
namewithanobjectreferenceoraclassnameandthememberaccessoperatoratother
times.Thefollowingrulesdispelthisconfusionbygivingyouguidanceonhowtoin-
voke methods from the various contexts:
• Specifythenameofaclassmethodasisfromanywherewithinthesameclass
as the class method. Example:
c2f(37.0);
• Specify the name of the class method's class, followed by the member access
operator, followed by the name of the class method from outside the class.
Example:
Conversions.c2f(37.0);
(Youcanalsoinvokeaclassmeth-
odviaanobjectinstance,butthatisconsideredbadformbecauseithidesfrom
casual observation the fact that a class method is being invoked.)
• Specify the name of an instance method as is from any instance method,
constructor, or instance initializer in the same class as the instance method.
Example:
setName(name);
• Specifyanobjectreference,followedbythememberaccessoperator,followed
by the name of the instance method from any class method or class initializer
within the same class as the instance method, or from outside the class.
Example:
Car
car
=
new
Car("Toyota",
"Camry");
car.printDetails();
Although the latter rule might seem to imply that you can call an instance method
from a class context, this is not the case. Instead, you call the method from an object
context.
Also, don't forget to make sure that the number of arguments passed to a method,
alongwiththeorderinwhichtheseargumentsarepassed,andthetypesoftheseargu-
ments agree with their parameter counterparts in the method being invoked.
Note
Field access and method call rules are combined in expression
Sys-
tem.out.println();
, where the leftmost member access operator accesses the
out
class field (of type
java.io.PrintStream
) in the
java.lang.System
class,andwheretherightmostmemberaccessoperatorcallsthisfield's
println()