美文网首页
this in java-1

this in java-1

作者: 落魄平生 | 来源:发表于2017-06-27 15:13 被阅读0次

The this
keyword is primarily used in three situations. The first and most common is in setter methods to disambiguate variable references. The second is when there is a need to pass the current class instance as an argument to a method of another object. The third is as a way to call alternate constructors from within a constructor.
Case 1: Using this
to disambiguate variable references. In Java setter methods, we commonly pass in an argument with the same name as the private member variable we are attempting to set. We then assign the argument x
to this.x
. This makes it clear that you are assigning the value of the parameter "name" to the instance variable "name".
public class Foo { private String name; public void setName(String name) { this.name = name; } }

Case 2: Using this
as an argument passed to another object.
public class Foo{ public String useBarMethod() { Bar theBar = new Bar(); return theBar.barMethod(this); } public String getName() { return "Foo"; } } public class Bar{ public void barMethod(Foo obj) { obj.getName(); } }

Case 3: Using this
to call alternate constructors. In the comments, trinithis correctly pointed out another common use of this
. When you have multiple constructors for a single class, you can use this(arg0, arg1, ...)
to call another constructor of your choosing, provided you do so in the first line of your constructor.
class Foo{ public Foo() { this("Some default value for bar"); //optional other lines } public Foo(String bar) { // Do something with bar }}

I have also seen this used to emphasize the fact that an instance variable is being referenced (sans the need for disambiguation), but that is a rare case in my opinion.

相关文章

  • Java-1

    容器基本内容 HashMap的底层 多线程同步方法 消息队列问题 设计模式中的生产者消费者模型 同步异步接口 My...

  • this in java-1

    The thiskeyword is primarily used in three situations. Th...

  • Java-1 求矩形面积

    目的:熟悉java基本的写法code:

网友评论

      本文标题:this in java-1

      本文链接:https://www.haomeiwen.com/subject/nydecxtx.html