打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

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


      使用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()方法表明,除构造器之外,编译器禁止在其他任何方法中调用构造方法。


本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Java中普通代码块,构造代码块,静态代码块区别
Java 方法 | 菜鸟教程
9个Java初始化和回收的面试题
婴儿的出生为你解惑构造函数和构造代码块
JAVA之关于This的用法
java之反射
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服