Next: None. Up: More about inheritance. Previous: The Object class.


Protection levels

Textbook: Section 11.2

We've been throwing around the public and private keywords, but we really haven't discussed them explicitly yet. Today we get to cover them.

Java actually has four levels of protection. These levels apply to both methods and variables (whether class members or instance members).

Frequently, it's a good idea to make instance variables protected instead of private. We might have done this with our balance instance variable in the Account class, for example.

public class Account {
    protected double balance;
    public Account() { balance = 0.0; }
    public double getBalance() { return balance; }
    public void deposit(double amt) { balance += amt; }
    public void withdraw(double amt) { balance += amt; }
}
If we did this, then the instance variable would be accessible within subclasses.
public class SavingsAccount extends Account {
    protected double interest;
    public SavingsAccount(double int) { interest = int; }
    public void addInterest() { balance += interest * balance; }
}
(This solves the problem we saw yesterday of how a class might override the deposit() method, making it so that addInterest() doesn't necessarily work as we intended when we wrote it.) But we're still forbidden from using the variable in other classes.
public class Main {
    public static void main(String[] args) {
        Account mine = new Account();
        IO.println(mine.balance); // ERROR: accessing protected member
    }
}


Next: None. Up: More about inheritance. Previous: The Object class.