开放-封闭原则
——对扩展开放,对修改封闭
1 package kaifangfenbi; 2 3 class Monkey { 4 public void PaShu() { 5 System.out.println("我是猴子,我会爬树!"); 6 } 7 } 8 9 // 六耳猕猴 10 class LiuErMiHou extends Monkey { 11 public void ChangSheng() { 12 System.out.println("俺老孙可以长生不老!"); 13 } 14 } 15 16 public class KaiFangFenBi { 17 18 public static void main(String[] args) { 19 // TODO Auto-generated method stub 20 21 LiuErMiHou liuErMiHou = new LiuErMiHou(); 22 System.out.println("六耳猕猴:"); 23 liuErMiHou.PaShu(); 24 liuErMiHou.ChangSheng(); 25 } 26 }
运行结果:
六耳猕猴:
我是猴子,我会爬树!
俺老孙可以长生不老!
1 package kaifangfenbi; 2 3 class Monkey { 4 public void PaShu() { 5 System.out.println("我是猴子,我会爬树!"); 6 } 7 } 8 9 // 六耳猕猴 10 class LiuErMiHou extends Monkey { 11 public void ChangSheng() { 12 System.out.println("俺老孙可以长生不老!"); 13 } 14 } 15 16 class SunWuKong extends LiuErMiHou { 17 public void QuJing() { 18 System.out.println("俺老孙是去西天拜佛求经的!"); 19 } 20 } 21 22 public class KaiFangFenBi { 23 24 public static void main(String[] args) { 25 // TODO Auto-generated method stub 26 27 LiuErMiHou liuErMiHou = new LiuErMiHou(); 28 System.out.println("六耳猕猴:"); 29 liuErMiHou.PaShu(); 30 liuErMiHou.ChangSheng(); 31 32 System.out.println("齐天大圣:"); 33 SunWuKong sunWuKong = new SunWuKong(); 34 sunWuKong.PaShu(); 35 sunWuKong.ChangSheng(); 36 sunWuKong.QuJing(); 37 } 38 }
运行结果:
六耳猕猴:
我是猴子,我会爬树!
俺老孙可以长生不老!
齐天大圣:
我是猴子,我会爬树!
俺老孙可以长生不老!
俺老孙是去西天拜佛求经的!
添加新类孙悟空,而非修改六耳猕猴类!!!