在
Java中使用“this”方法呢?是否有选择性或有需要使用强制性的情况?
我遇到的唯一情况是在类中调用方法中的方法.但它是可选的.这是一个愚蠢的例子,只是为了显示我的意思:
public class Test {
String s;
private String hey() {
return s;
}
public String getS(){
String sm = this.hey();
// here I Could just write hey(); without this
return sm;
}
}
解决方法
你需要的三个明显的情况:
>调用与构造函数的第一部分相同的类中的另一个构造函数
>区分局部变量和实例变量(无论是在构造函数还是其他方法中)
>将当前对象的引用传递给另一种方法
以下是三个例子:
public class Test
{
int x;
public Test(int x)
{
this.x = x;
}
public test()
{
this(10);
}
public void foo()
{
Helper.doSomethingWith(this);
}
public void setX(int x)
{
this.x = x;
}
}
我相信还有一些奇怪的情况,使用内部类,你需要super.this.x,但是应该避免它们非常晦涩,IMO
总结
以上是DEVMAX为你收集整理的使用“this”与方法(在Java中)全部内容。
如果觉得DEVMAX网站内容还不错,欢迎将DEVMAX网站推荐给好友。