分享

Java构造器中,不能用this同时调用两个构造器

 寂寞如故 2013-12-21


      使用this在构造器中调用构造器,通常写this的时候,都是指“这个对象”或者“当前对象”,而且它本身表示对当前对象的引用。在构造器中,如果为this添加了参数列表,那么就有了不同的含义。这将产生对符合此参数列表的某个构造器的明确调用;这样,调用其他构造器就有了直接的途径:

Java代码

public class Flower{

int petalCount=0;

String s="initial value";

Flower(int petals){

petalCount=petals;

System.out.print("Constructor w/int arg only,petalCount=.."+petalCount);

}

Flower(String ss){

System.out.print("Constructor w/String arg only,s="+ss);

s=ss;

}

Flower(String s,int petals){

this(petals);

this(s); //Can't call two!

this.s=s; //Another use of"this"

System.out.print("String&int args");

}


public void printPetel(){

// this(11);

System.out.print( "petalCount=.."+petalCount+ "s="+ss);

}

}

注:printPetel()方法表明,除构造器之外,编译器禁止在其他任何方法中调用构造方法。


    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多