这章最后主要讲了复用:继承复用和组合复用,分别举了个例子来说明:
继承:eg
- class Animal
- {
- private void beat()
- {
- System.out.println("心脏跳动...");
- }
- public void breath()
- {
- beat();
- System.out.println("吸一口气,吐一口气,呼吸中...");
- }
- }
- //继承Animal,直接复用父类的breath方法
- class Bird extends Animal
- {
- public void fly()
- {
- System.out.println("我在天空自在的飞翔...");
- }
- }
- //继承Animal,直接复用父类的breath方法
- class Wolf extends Animal
- {
- public void run()
- {
- System.out.println("我在陆地上的快速奔跑...");
- }
- }
- public class TestInherit
- {
- public static void main(String[] args)
- {
- Bird b = new Bird();
- b.breath();
- b.fly();
- Wolf w = new Wolf();
- w.breath();
- w.run();
- }
- }
组合:
- class Animal
- {
- private void beat()
- {
- System.out.println("心脏跳动...");
- }
- public void breath()
- {
- beat();
- System.out.println("吸一口气,吐一口气,呼吸中...");
- }
- }
- class Bird
- {
- //将原来的父类嵌入原来的子类,作为子类的一个组合成分
- private Animal a;
- public Bird(Animal a)
- {
- this.a = a;
- }
- //重新定义一个自己的breath方法
- public void breath()
- {
- //直接复用Animal提供的breath方法来实现Bird的breath方法。
- a.breath();
- }
- public void fly()
- {
- System.out.println("我在天空自在的飞翔...");
- }
- }
- class Wolf
- {
- //将原来的父类嵌入原来的子类,作为子类的一个组合成分
- private Animal a;
- public Wolf(Animal a)
- {
- this.a = a;
- }
- //重新定义一个自己的breath方法
- public void breath()
- {
- //直接复用Animal提供的breath方法来实现Bird的breath方法。
- a.breath();
- }
- public void run()
- {
- System.out.println("我在陆地上的快速奔跑...");
- }
- }
- public class TestComposite
- {
- public static void main(String[] args)
- {
- //此时需要显式创建被嵌入的对象
- Animal a1 = new Animal();
- Bird b = new Bird(a1);
- b.breath();
- b.fly();
- //此时需要显式创建被嵌入的对象
- Animal a2 = new Animal();
- Wolf w = new Wolf(a2);
- w.breath();
- w.run();
- }
- }
后面讲了初始化块,以前不怎么用,刚知道他还分静态初始化和普通初始化。这个没什么好说的看代码就知道了。eg
- class Root
- {
- static{
- System.out.println("Root的静态初始化块");
- }
- {
- System.out.println("Root的普通初始化块");
- }
- public Root()
- {
- System.out.println("Root的无参数的构造器");
- }
- }
- class Mid extends Root
- {
- static{
- System.out.println("Mid的静态初始化块");
- }
- {
- System.out.println("Mid的普通初始化块");
- }
- public Mid()
- {
- System.out.println("Mid的无参数的构造器");
- }
- public Mid(String msg)
- {
- //通过this调用同一类中重载的构造器
- this();
- System.out.println("Mid的带参数构造器,其参数值:" + msg);
- }
- }
- class Leaf extends Mid
- {
- static{
- System.out.println("Leaf的静态初始化块");
- }
- {
- System.out.println("Leaf的普通初始化块");
- }
- public Leaf()
- {
- //通过super调用父类中有一个字符串参数的构造器
- super("Struts2权威指南");
- System.out.println("执行Leaf的构造器");
- }
- }
- public class Test
- {
- public static void main(String[] args)
- {
- new Leaf();
- new Leaf();
- }
- }
本章练习
1.定义普通人,老师,班主任,学生,学校,提供适当属性和方法。。。。(这题比较空,我就用rose搞下)
2.上题用组合实现(也就把普通人对象通过构造传入,这太无聊了就不做了)
本文详细探讨了面向对象编程中的两种复用方式:继承复用和组合复用,并通过具体示例进行了阐述。同时介绍了静态初始化块与普通初始化块的概念及其执行顺序。
287

被折叠的 条评论
为什么被折叠?



