File tree Expand file tree Collapse file tree 1 file changed +37
-1
lines changed
Expand file tree Collapse file tree 1 file changed +37
-1
lines changed Original file line number Diff line number Diff line change 1818
1919<!-- Composition Syntax -->
2020## 组合语法
21-
21+ 在前面的学习中,“组合”(** Composition** )已经被多次使用。你仅需要把对象的引用(** object references** )放置在一个新的类里,这就使用了组合。例如,假设你需要一个对象,其中内置了几个String对象,两个基本类型(** primitives** )的属性字段,一个自定义Class的对象。对于非基本类型对象,将引用直接放置在Class中,对于基本类型属性字段则仅进行声明(** define** )。
22+ // reuse/SprinklerSystem.java
23+ // Composition for code reuse
24+ class WaterSource {
25+ private String s;
26+ WaterSource() {
27+ System.out.println("WaterSource()");
28+ s = "Constructed";
29+ }
30+ @Override
31+ public String toString() { return s; }
32+ }
33+ public class SprinklerSystem {
34+ private String valve1, valve2, valve3, valve4;
35+ private WaterSource source = new WaterSource();
36+ private int i;
37+ private float f;
38+ @Override
39+ public String toString() {
40+ return
41+ "valve1 = " + valve1 + " " +
42+ "valve2 = " + valve2 + " " +
43+ "valve3 = " + valve3 + " " +
44+ "valve4 = " + valve4 + "\n" +
45+ "i = " + i + " " + "f = " + f + " " +
46+ "source = " + source; // [ 1]
47+ }
48+ public static void main(String[ ] args) {
49+ SprinklerSystem sprinklers = new SprinklerSystem();
50+ System.out.println(sprinklers);
51+ }
52+ }
53+ /* Output:
54+ WaterSource()
55+ valve1 = null valve2 = null valve3 = null valve4 = null
56+ i = 0 f = 0.0 source = Constructed
57+ * /
2258
2359<!-- Inheritance Syntax -->
2460## 继承语法
You can’t perform that action at this time.
0 commit comments