Java Reference
In-Depth Information
. . .
}
The compiler does not allow this, because the increased privacy would be an
illusion. Anyone can still call the method through a superclass reference:
BankAccount account = new CheckingAccount();
account.withdraw(100000); // Calls
CheckingAccount.withdraw
Because of polymorphism, the subclass method is called.
These errors are usually an oversight. If you forget the
public
modifier, your
subclass method has package access, which is more restrictive. Simply restore the
public
modifier, and the error will go away.
A
DVANCED
T
OPIC
10.3: Protected Access
We ran into a hurdle when trying to implement the
deposit
method of the
CheckingAccount
class. That method needed access to the
balance
instance
field of the superclass. Our remedy was to use the appropriate method of the
superclass to set the balance.
Java offers another solution to this problem. The superclass can declare an instance
field as protected:
public class BankAccount
{
. . .
protected double balance;
}
Protected data in an object can be accessed by the methods of the object's class and
all its subclasses. For example,
CheckingAccount
inherits from
BankAccount
, so its methods can access the protected instance fields of the
BankAccount
class. Furthermore, protected data can be accessed by all methods
of classes in the same package.
Protected features can be accessed by all subclasses and all classes in the
same package.