Java Reference
In-Depth Information
Apart from making the method main() , perhaps the most common use for class methods is when a
class is just used to contain a bunch of utility methods, rather than as a specification for objects. All
executable code in Java has to be within a class, but there are lots of general-purpose functions that you
need that don't necessarily have an object association - calculating a square root, for instance, or
generating a random number. For example, the mathematical functions that are implemented as class
methods in the standard class Math , don't relate to class objects at all - they operate on values of the
basic types. You don't need objects of type Math , you just want to use the methods from time to time,
and you can do this as we saw in Chapter 2. The class Math also contains some class variables
containing useful mathematical constants such as e and
π
.
Accessing Variables and Methods
You will often want to access variables and methods, defined within a class, from outside it. We will see
later that it is possible to declare class members with restrictions on accessing them from outside, but
let's cover the principles that apply where the members are accessible. We need to consider accessing
static members and instance members separately.
You can access a static member of a class using the class name, followed by a period, followed by the
member name. With a class method you will also need to supply the parentheses enclosing any
arguments to the method after the method name. The period here is called the dot operator. So, if you
wanted to calculate the square root of
you could access the class method sqrt() and the class
variable PI that are defined in the Math class as follows:
π
double rootPi = Math.sqrt(Math.PI);
This shows how you call a static method - you just prefix it with the class name and put the dot
operator between them. We also reference the static data member, PI , in the same way - as Math.PI .
If you have a reference to an object of a class type available, then you can also use that to access a static
member of a class method. You just use the variable name, followed by the dot operator, followed by
the member name.
Instance variables and methods can only be called using an object reference, as by definition they relate to a
particular object. The syntax is exactly the same as we have outlined for static members. You put the name of
the variable referencing the object followed by a period, followed by the member name. To use a method
volume() that has been declared as an instance method in the Sphere class, you might write:
double ballVolume = ball.volume();
Here the variable ball is of type Sphere and it contains a reference to an object of this type. We call
its volume() method that calculates the volume of the ball object, and the result that is returned is
stored in the variable, ballVolume .
Search WWH ::




Custom Search