//: polymorphism/Transmogrify.java // Dynamically changing the behavior of an object // via composition (the "State" design pattern). import static net.mindview.util.Print.*; class Actor { public void act() {} } class HappyActor extends Actor { public void act() { print("HappyActor"); } } class SadActor extends Actor { public void act() { print("SadActor"); } } class Stage { private Actor actor = new HappyActor(); public void change() { actor = new SadActor(); } public void performPlay() { actor.act(); } } public class Transmogrify { public static void main(String[] args) { Stage stage = new Stage(); stage.performPlay(); stage.change();// 状态的改变 stage.performPlay(); } } /* Output: HappyActor SadActor *///:~
//: polymorphism/PolyConstructors.java // Constructors and polymorphism // don‘t produce what you might expect. import static net.mindview.util.Print.*; class Glyph { void draw() { print("Glyph.draw()"); } Glyph() { print("Glyph() before draw()"); draw();// 执行这个方法时候,调用的其实是被覆盖以后的方法 print("Glyph() after draw()"); } } class RoundGlyph extends Glyph { private int radius = 1;//执行这一步以前, 会先执行父类的构造器, 然后父类的构造器又会直接调用覆盖以后的方法 RoundGlyph(int r) { radius = r; print("RoundGlyph.RoundGlyph(), radius = " + radius); } void draw() { print("RoundGlyph.draw(), radius = " + radius); } } public class PolyConstructors { public static void main(String[] args) { new RoundGlyph(5); } } /* Output: Glyph() before draw() RoundGlyph.draw(), radius = 0 Glyph() after draw() RoundGlyph.RoundGlyph(), radius = 5 *///:~
Think In Java 多态学习,布布扣,bubuko.com
原文:http://www.cnblogs.com/driftsky/p/3627352.html