关于 “this”用法的疑惑

thowoo 2016-07-04 10:37:33
刚刚开始自学java,有一处十分疑惑: You can also use the keyword this in a constructor to invoke one of the other constructors for this object。

我的理解是this只是指向现在所在的constructor,怎么还能调用其他的constructor。有点不解,十分感激哪位前辈能给解解惑。
...全文
107 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
qq_15915835 2016-07-04
  • 打赏
  • 举报
回复
this 表示的对象。this.method 表示调用对象的方法,在方法调用时候可以省略。构造器也可以理解成特殊的方法this在一个构造方法调用另一个构造方法时不能省略

public class Test{
 public Test(){
  this(test);
 }
 public Test(String s){
   //
}
}
LotusQ 2016-07-04
  • 打赏
  • 举报
回复
个人感觉是为了维护时方便增删对某些实例域的初始化。
公子寻欢 2016-07-04
  • 打赏
  • 举报
回复
You can also use the keyword this in a constructor to invoke one of the other constructors for this object。 你也可以在构造器里使用关键字this,来引用这个对象的另外一个构造器。 this指代的是当前对象,不仅仅是指向其所在的constructor

public class Demo {
	
	private String name;

	public Demo() {}

	public Demo(String name) {
		
		this();		// 调用空参的构造器来构造出对象,再对其name进行赋值
		this.name = name;
	}
}

50,523

社区成员

发帖
与我相关
我的任务
社区描述
Java相关技术讨论
javaspring bootspring cloud 技术论坛(原bbs)
社区管理员
  • Java相关社区
  • 小虚竹
  • 谙忆
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧