组合 新类中产生 现有类的对象
继承 现有类的形式并其中添加新代码

组合语法

将对象置于新类:直接定义基本类型;非基本类型对象,引用置于新类;

package chapter7reusing;
// Composition for code reuse.

class WaterSource {
    private String s;

    WaterSource() {
        System.out.println("WaterSource()");
        s = "Constructed";
    }

    public String toString() { //每一个非基本类型对象都有 toString方法
        return s;
    }
}

public class SprinklerSystem {
    private String valve1, valve2, valve3, valve4;
    private WaterSource source = new WaterSource();
    private int i;
    private float f;

    public String toString() {
        return
                "valve1 = " + valve1 + " " +
                        "valve2 = " + valve2 + " " +
                        "valve3 = " + valve3 + " " +
                        "valve4 = " + valve4 + " " +
                        "i = " + i + " " +
                        "f = " + f + " " +
                        "source = " + source;//调用toString(),将source对象转换为String
    }

    public static void main(String[] args) {
        SprinklerSystem sprinklerSystem = new SprinklerSystem();
        System.out.println(sprinklerSystem); // 基本类型 初始化为0 对象引用初始化为null
    }
}
/* outpub:
WaterSource()
valve1 = null valve2 = null valve3 = null valve4 = null i = 0 f = 0.0 source = Constructed

四种方式初始化

  1. 定义对象的地方
  2. 类的构造器
  3. 惰性初始化
  4. 使用实例初始化
package chapter7reusing;
//Constructor initialization with composition

import static chapter6access.Print.print;

class Soap {
    private String s;

    Soap() { // 类的构造器中
        print("Soap()");
        s = "Constructed";
    }

    public String toString() {
        return s;
    }

}

public class Bath {
    private String //定义对象的地方初始化,构造器被调用之前初始化
            s1 = "Happy",
            s2 = "Happy",
            s3, s4;
    private Soap castille;
    private int i;
    private float toy;

    public Bath() {
        print("Inside Bath()");
        s3 = "Joy";
        toy = 3.14f;
        castille = new Soap(); // 使用实例初始化
    }

    {
        i = 47;
    }

    public String toString() {
        if (s4 == null) //惰性初始化:使用对象之前初始化
            s4 = "Joy";
        return
                "s1 = " + s1 + "\n" +
                        "s2 = " + s2 + "\n" +
                        "s3 = " + s3 + "\n" +
                        "s4 = " + s4 + "\n" +
                        "i = " + i + "\n" +
                        "toy = " + toy + "\n" +
                        "castille = " + castille;
    }

    public static void main(String[] args) {
        Bath bath = new Bath();
        print(bath);
    }

}
12-27 20:32
查看更多