构造器中调用构造器(Java编程思想摘要)

    一个类写了多个构造器,有时可能想在一个构造器中调用另一个构造器,以避免重复代码,可用this关键字做到这一点。

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

public class Flower{

    int petalCount = 0;

    String s = "initial value";

    Flower(String ss){

        system.out.println("Constructor int arg only,petalCount= "+petalCount);

    }

    Flower(String s,int petals){

        this(petals);

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

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

        system.out.println("String & int args");

    }

    Flower(){

        this("hi",47);

        system.out.println("default constructor (no args)");

    }

    void printPetalCount(){

        //this(11); //Not inside non-constructor!

         system.out.println("petalCount = " + petalCount + " s = "+s);

    }

    public static void main(String[] args){

        Flower x = new Flower();

        x.printPetalCount();

    }

} 

    

打印信息:

 

   Constructor int arg only,petalCount= 47

   String & int args

   default constructor (no args)

   petalCount = 47  s = hi

 

    构造器Flower(String s,int  petals) 表明:  尽管可以用this调用一个构造器,但是不能调用两个。此外,必须将构造器调用置于最起始处,否则编译器会报错。

    这个例子也展示了this的另一种用法。由于参数s的名称·和数据成员s的名字相同,所以会产生歧义,使用this.s来代表数据成员就能解决这个问题。

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值