使用“this”用方法(用Java) [英] Using "this" with methods (in Java)
问题描述
在Java中使用this和方法怎么样?它是可选的还是有必要使用它的情况?
what about using "this" with methods in Java? Is it optional or there are situations when one needs to use it obligatory?
我遇到的唯一情况是在类中调用方法中的方法。但它是可选的。这是一个愚蠢的例子,只是为了表明我的意思:
The only situation I have encountered is when in the class you invoke a method within a method. But it is optional. Here is a silly example just to show what I mean:
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:)
I believe there are also some weird situations using inner classes where you need super.this.x
but they should be avoided as hugely obscure, IMO :)
编辑:我想不出任何一个例子,为什么你想要它直接 this.foo()
方法调用。
I can't think of any examples why you'd want it for a straight this.foo()
method call.
编辑:saua在内部类别模糊的问题上做出了贡献:
saua contributed this on the matter of obscure inner class examples:
我认为不明显的案例是:
OuterClass.this.foo()
从Inner类中的代码访问外部
类的foo()
时还有一个foo()
方法。
I think the obscure case is:
OuterClass.this.foo()
when accessingfoo()
of the outer class from the code in an Inner class that has afoo()
method as well.
这篇关于使用“this”用方法(用Java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!