Dynamically changing the behavior of an object via composition (the 'State' design pattern) : Class Fields « Class Definition « Java Tutorial






abstract class Actor {
  public abstract void act();
}

class HappyActor extends Actor {
  public void act() {
    System.out.println("HappyActor");
  }
}

class SadActor extends Actor {
  public void act() {
    System.out.println("SadActor");
  }
}

class Stage {
  private Actor actor = new HappyActor();

  public void change() {
    actor = new SadActor();
  }

  public void performPlay() {
    actor.act();
  }
}

public class MainClass {
  public static void main(String[] args) {
    Stage stage = new Stage();
    stage.performPlay();
    stage.change();
    stage.performPlay();
  }
}
HappyActor
SadActor








5.4.Class Fields
5.4.1.Scope class demonstrates field and local variable scopes
5.4.2.Dynamically changing the behavior of an object via composition (the 'State' design pattern)
5.4.3.Scope for Class and Local Variables
5.4.4.A Class that Demonstrates Shadowing