Java Reference
In-Depth Information
That is, you don't call
double x = 4;
double root = x.sqrt(); // Error
153
154
because, in Java, numbers are not objects, so you can never invoke a method on a
number. Instead, you pass a number as an explicit parameter to a method, enclosing
the number in parentheses after the method name. For example, the number value x
can be a parameter of the Math.sqrt method: Math.sqrt(x) .
This call makes it appear as if the sqrt method is applied to an object called Math ,
because Math precedes sqrt just as harrysChecking precedes getBalance
in a method call harrysChecking.getBalance() . However, Math is a class,
not an object. A method such as Math.round that does not operate on any object is
called a static method. (The term ȓstaticȓ is a historical holdover from the C and C++
programming languages. It has nothing to do with the usual meaning of the word.)
Static methods do not operate on objects, but they are still defined inside classes. You
must specify the class to which the sqrt method belongsȌhence the call is
Math.sqrt(x) .
A static method does not operate on an object.
How can you tell whether Math is a class or an object? All classes in the Java library
start with an uppercase letter (such as System ). Objects and methods start with a
lowercase letter (such as out and println ). (You can tell objects and methods
apart because method calls are followed by parentheses.) Therefore,
System.out.println() denotes a call of the println method on the out
object inside the System class. On the other hand, Math.sqrt(x) denotes a call
to the sqrt method inside the Math class. This use of upper- and lowercase letters is
merely a convention, not a rule of the Java language. It is, however, a convention that
the authors of the Java class libraries follow consistently. You should do the same in
your programs. If you give names to objects or methods that start with uppercase
letters, you will likely confuse your fellow programmers. Therefore, we strongly
recommend that you follow the standard naming convention.
S YNTAX 4.3 Static Method Call
ClassName.methodName (parameters)
Search WWH ::




Custom Search