Java Reference
In-Depth Information
mathematics tell us that the sum of two nonnegative numbers is again nonnegative,
so we can conclude that balance >= 0 after the completion of the deposit .
Thus, the deposit method preserves the invariant.
A similar argument shows that the withdraw method preserves the invariant.
Because the invariant is a property of the class, you document it with the class
description:
/**
A bank account has a balance that can be changed by
deposits and withdrawals.
(Invariant: getBalance() >= 0)
*/
public class BankAccount
{
. . .
}
8.6 Static Methods
Sometimes you need a method that is not invoked on an object. Such a method is
called a static method or a class method. In contrast, the methods that you wrote up to
now are often called instance methods because they operate on a particular instance
of an object.
A static method is not invoked on an object.
A typical example of a static method is the sqrt method in the Math class. When
you call Math.sqrt(x) , you don't supply any implicit parameter. (Recall that
Math is the name of a class, not an object.)
Why would you want to write a method that does not operate on an object? The most
common reason is that you want to encapsulate some computation that involves only
numbers. Because numbers aren't objects, you can't invoke methods on them. For
example, the call x.sqrt() can never be legal in Java.
Search WWH ::




Custom Search