java中组合语法

来源:互联网 发布:vivo的软件商店 编辑:程序博客网 时间:2024/05/17 06:06

组合语法

什么叫组合技术,顾名思义就是一个类里面引用其他的对象。直接上代码说话。
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()Constructedvalve1 = 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;    }}
惰性加载:需要用到这个引用时,我们才去对它进行初始化!这样可以大大减少编译器的负担
                      


原创粉丝点击