Sams Teach Yourself Java™ in 24 Hours (Covering Java 7 and Android)

(singke) #1
ptg7068951

142 HOUR 11:Describing What Your Object Is Like


You can use any method that returns a value at any place in the program
where you could use a variable.
Earlier in the hour, you switched the newSecondsvariable to privateto
prevent it from being read or modified by other programs. There’s still a
way to make it possible for newSecondsto be used elsewhere: Create
publicmethods in the Virusclass that get the value of newSecondsand set
newSecondsto a new value. These new methods should be public, unlike
the newSecondsvariable itself, so they can be called in other programs.
Consider the following two methods:
public intgetSeconds() {
return newSeconds;
}

public voidsetSeconds(int newValue) {
if (newValue > 60) {
newSeconds = newValue;
}
}

These methods are called accessormethods because they enable the
newSecondsvariable to be accessed from other objects.
The getSeconds()methodis used to retrieve the current value of
newSeconds. The getSeconds()method does not have any arguments, but
it still must have parentheses after the method name. The setSeconds()
methodtakes one argument, an integer called newValue. This argument is
the new value of newSeconds. If newValueis greater than 60, the change
will be made.
In this example, the Virusclass controls how the newSecondsvariable can
be used by other classes. This process is called encapsulation, and it’s a fun-
damental concept of OOP. The better your objects are able to protect them-
selves against misuse, the more useful they are when you use them in
other programs.
Though newSecondsis private, the new methods getSeconds()and
setSeconds()are able to work with newSecondsbecause they are in the
same class.

Similar Methods with Different Arguments
As you have seen with the setSeconds()method, you can send arguments
to a method to affect what it does. Different methods in a class can have
Free download pdf