课后习题:练习1:创建一个简单的类,在第二个类中,将引用定义为第一个类的对象。运用惰性初始化来实例化这个对象。

我的答案:

一,个人。

 1 package com.learnJava.test;
 2 
 3 /**
 4  * @Author zhuchangli
 5  * @Date 2019/9/14
 6  **/
 7 
 8 // 灶具
 9 class Cooker{
10     private String pot; //
11     private String gas; // 煤气
12     Cooker(){
13         pot = "Constructed pot";
14         gas = "Constructed gas";
15     }
16 
17     public String toString(){
18         return "pot = " + pot + "\n" +
19                 "gas = " + gas + "\n" ;
20     }
21 }
22 // 厨房
23 public class Kitchen {
24     private String s1 = "happy";
25     private String s2 = "happy";
26     private String s3;
27     private float s4;
28     private Cooker cooker;
29 
30     public Kitchen(){
31         System.out.println("Inside Cooker");
32         s3 = "day";
33         s4 = 3.14f;
34         cooker = new Cooker();
35     }
36 
37     public String toString(){
38         return "s1 = " + s1 + "\n" +
39                 "s2 = " +s2 + "\n" +
40                 "s3 = " +s3+ " \n" +
41                 "s4 =" +s4+ "\n" +
42                 "cooker= " +cooker+ "\n";
43     }
44 
45     public static void main(String [] args){
46         Kitchen kitchen = new Kitchen();
47         System.out.println(kitchen);
48     }
49 }

 

 二,参考答案写的

 1 package com.learnJava.test;
 2 
 3 /**
 4  * @Author zhuchangli
 5  * @Date 2019/9/14
 6  **/
 7 
 8 // 轮子
 9 class Cycle{
10     private String name = "Cycle";
11     public void travle(Cycle c){
12         System.out.println("Cycle ride "+ c );
13     }
14     public String toString(){
15         return this.name;
16     }
17 }
18 
19 class Unicycle extends Cycle{
20 
21     private String name = "Unicycle";
22 
23     public String toString(){
24         return this.name;
25     }
26 }
27 
28 class Bicycle extends Cycle{
29 
30     private String name = "Bicycle";
31 
32     public String toString(){
33         return this.name;
34     }
35 }
36 
37 class Tricycle extends Cycle{
38     private String name = "Tricycle";
39 
40     public String toString(){
41         return this.name;
42     }
43 }
44 
45 // 骑行
46 public class Biking {
47 
48     public static void ride(Cycle c){
49         c.travle(c);
50     }
51 
52     public static void main(String [] args){
53 
54         Unicycle u = new Unicycle();
55         Bicycle b = new Bicycle();
56         Tricycle t = new Tricycle();
57 
58         ride(u);
59         ride(b);
60         ride(t);
61     }
62 }

三,总结

1,组合技术,只需要将对象引用置于新类中即可。

2,每一个非基本类型的对象都有一个toString方法,当编译器需要一个String而你只有一个对象时,自己定义的toString 方法便会被调用。

3,编译器并不是简单的为每一个引用都创建默认对象。

4,想初始化这些引用可以在 一下位置进行。

  a,在定义对象的地方,意味着总是能够在构造器被调用之前被初始化。

  b,在类的构造器中。

  c,惰性初始化,在正要使用这些对象之前使用,在生成对象不值得及不必每次都生成对象的情况下,这种方式可以减少额外的负担。

  d,使用实例初始化。

 posted on 2019-09-14 09:43  岂曰-无衣  阅读(259)  评论(0编辑  收藏  举报