SE450: Inner Classes: Non-static [11/22] Previous pageContentsNext page

When talking about non-static nested classes, we refer to them as inner classes. You need an instance of the outer class to instantiate the inner class.

For example:

public class BankAccount {
  private long number;
  private long balance;
  private Action lastAct;

  public class Action {
    private String act;
    private long amount;
    Action(String act, long amount) {
      this.act = act;
      this.amount = amount;
    }
    public String toString() {
      return number + ": " + act + " " + amount;
    }
  }

  public void deposit(long amount) {
    balance += amount;
    lastAct = new Action("deposit", amount);
  }  

  public void withdraw(long amount) {
    balance -= amount;
    lastAct = new Action("withdraw", amount);
  }  
  // ...
}

the creation of the Action could be written more explicitly as lastAct = this.new Action("deposit", amount); . Outside the BankAccount class, this would look like this:

BankAccount ba = new BankAccount();
Action act = ba.new Action("deposit", 4);

A nested class can use other members of the enclosing class without qualification (including private fields). A static nested class (last slide) can directly access only static members of the enclosing class.

The toString() method above could be written as return BankAccount.this.number + ": " + act + " " + amount; This is the way that you access the outer class from the inner class if you need to explicitly accesss an enclosing class's members.

It is recommended that you only nest classes one deep, but any level is allowed.

Inner classes can't have static members.

Previous pageContentsNext page