java中组合语法

组合语法

什么叫组合技术,顾名思义就是一个类里面引用其他的对象。直接上代码说话。
package reuse;

/**
 * 洒水系统
 */

public class SpringkerSystem {
    //定义几个阀门
    private String valve1,valve2,valve3;
    private WaterSource source = new WaterSource();
    private int i;
    private float f;

    public String toString(){
        System.out.println(source);
        return  "valve1 = " + valve1 + " " +
                "valve2 = " + valve2 + " " +
                "valve3 = " + valve3 + " " +
                "source = " + source + " " +
                "i = " + i +
                "f = " + f ;
    }

    public static void main(String[] args) {
        SpringkerSystem springkerSystem = new SpringkerSystem();
        System.out.println(springkerSystem);
    }
}

class WaterSource {

    private String s;

    WaterSource() {
        //输出水源
        System.out.println("WaterSource()");
        //已经调用构造函数
        s = "Constructed";
    }

    public String toString() {
        return s;
    }
}
OUTPUT:
WaterSource()
Constructed
valve1 = null valve2 = null valve3 = null source = Constructed i = 0f = 0.0

这是一个洒水系统类,这里还有一个水源对象,洒水系统如果想实现,则必须依赖水源这个对象!来看程序本身,这里本来输出的是一个对象,我们正常看到输出一
个对象应该是包名+对象+哈希值,但是这里由于重写了toString()方法,所以编译器会默认调用这个方法,从而会输出toString()方法里面的返回值!当然这里并没有给
引用初始化,编译器会给引用初始化!下面则是初始化引用的四个位置:
package reuse;

public class Bath {
    private String
            s1 = "Happy",//1.在构造器调用之前初始化  Initailizing at ponit of definition
            s2 = "Said",
            s3, s4;
    private Soap soap;
    private int i;
    private float toy;

    public Bath() {
        System.out.println("Bath()");
        s3 = "joy";//2.在构造器中初始化   contructe initailization
        toy = 3.14f;
        soap = new Soap();
    }

    {
        i = 17;//3.使用实例初始化  instance initailization
    }

    public String toString() {
        if (s4 == null) s4 = "joy"; //3.惰性初始化 Delayed initailiztion
        return "s1 = " + s1 + "\n" +
                "s2 = " + s2 + "\n" +
                "s3 = " + s3 + "\n" +
                "s4 = " + s4 + "\n" +
                "soup = " + soap + "\n" +
                "toy = " + toy + "\n" +
                "i = " + i;
    }

    public static void main(String[] args) {
        Bath bath = new Bath();
        System.out.println(bath);
    }
}

class Soap {
    private String s;

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

    public String toString() {
        return s;
    }
}
惰性加载:需要用到这个引用时,我们才去对它进行初始化!这样可以大大减少编译器的负担
                      


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱折腾的Albert

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值