Java Reference
In-Depth Information
with what static methods do. Indeed, it's used by accident. Java uses the static
keyword because C++ uses it in the same context. C++ uses static to denote class
methods because the inventors of C++ did not want to invent another keyword.
Someone noted that there was a relatively rarely used keyword, static , that
denotes certain variables that stay in a fixed location for multiple method calls. (Java
does not have this feature, nor does it need it.) It turned out that the keyword could be
reused to denote class methods without confusing the compiler. The fact that it can
confuse humans was apparently not a big concern. You'll just have to live with the
fact that Ȓstatic methodȓ means Ȓclass methodȓ: a method that does not operate on an
object and that has only explicit parameters.
S ELF C HECK
12. Suppose Java had no static methods. Then all methods of the Math
class would be instance methods. How would you compute the square
root of x?
13. Harry turns in his homework assignment, a program that plays
tic-tac-toe. His solution consists of a single class with many static
methods. Why is this not an object-oriented solution?
353
354
8.7 Static Fields
Sometimes, you need to store values outside any particular object. You use static
fields for this purpose. Here is a typical example. We will use a version of our
BankAccount class in which each bank account object has both a balance and an
account number:
public class BankAccount
{
. . .
private double balance;
private int accountNumber;
}
We want to assign account numbers sequentially. That is, we want the bank account
constructor to construct the first account with number 1001 , the next with number
1002 , and so on. Therefore, we must store the last assigned account number
somewhere.
Search WWH ::




Custom Search