2012-06-06 195 views
1

可能重复:
Java this.method() vs method()“这”是什么意思?

我一直在读了一些东西,做关于Android的Java一些教程,但我还是不明白什么是“这个”手段,如下面的代码。

View continueButton = this.findViewById(R.id.continue_button); 
    continueButton.setOnClickListener(this); 
    View newButton = this.findViewById(R.id.new_button); 
    newButton.setOnClickListener(this); 

此外,为什么它在这个例子中,一个按钮没有定义与按钮,但与视图,有什么区别?

ps。伟大的网站!试图通过在这里搜索学习java并获得ALLOT的答案!

+0

你不会知道。因为'this'是代码存在的方法的接收者。由于我们没有代码,我们无法回答。 –

+2

以下是[this]的官方Java解释(http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html)。 – Sam

+0

@Mark不一定是这个问题的一个骗局,因为OP也询问'setOnClickListener(this)' –

回答

4

this关键字是a reference to the current object。它用于通过这个实例的对象,等等。

例如,这两个分配是平等的:

class Test{ 

    int a; 

    public Test(){ 
     a = 5; 
     this.a = 5; 
    } 

} 

有时你有一个隐藏的领域要访问:

class Test{ 

    int a; 

    public Test(int a){ 
     this.a = a; 
    } 

} 

在这里,你在参数分配领域a与价值a

this关键字与方法的工作方式相同。同样,这两个是相同的:

this.findViewById(R.id.myid); 
findViewById(R.id.myid); 

最后,说你有这需要一个MyObject的参数的方法的类的MyObject:

class MyObject{ 

    public static void myMethod(MyObject object){ 
     //Do something 
    } 

    public MyObject(){ 
     myMethod(this); 
    } 

} 

在最后这个例子中,你通过的一个参考当前对象为静态方法。

此外,为什么它在这个例子中,按钮没有定义与按钮,但与视图有什么区别?

在Android SDK中,一个ButtonView一个subclass。您可以要求ButtonViewcastViewButton

Button newButton = (Button) this.findViewById(R.id.new_button); 
0

“this”是当前的对象实例。

class Blaa 
{ 
    int bar=0; 
    public Blaa() 
    {} 
    public void mogrify(int bar,Blaa that) 
    { 
     bar=1; //changes the local variable bar 
     this.bar=1; //changes the member variable bar. 
     that.bar=1; //changes "that"'s member variable bar. 
    } 

} 
0

this是指一类

+0

'this'不是当前实例。它是一个指向当前实例的指针。 –

+0

@JayD在上面的答案中注意到了“引用”这个词,在Java中只有引用有_no_指针。 –

+0

检查此关键字的链接.. http://www.javabeat.net/qna/16-what-is-super-and-this-keyword-in-java/ – swiftBoy

1

this指的是正在采取行动的对象实例的当前实例。

在你有以上的情况下,this.findViewById(R.id.continue_button)这指的是一个方法在父类(具体要么Activity.findViewById()View.findViewByid(),假设你正在写自己的ActivityView子!)。在Java中是

+0

该代码可以放在一个自定义的视图和它仍然可以很好地工作。说它唯一的Activity.findViewById()并不完全正确。 – HandlerExploit

+0

“this.someMethod”不一定会调用父类中的方法。事实上,'this'不会在这种情况下添加信息,就像'super'那样。 (除非通过“父类”你的意思是“这个实例的类)。 –

+1

@HandlerExploit谢谢你指出,我会相应地更新。 –

0

this是对当前对象实例的引用。因此,如果您正在编写MyClass类的方法,则thisMyClass的当前实例。

请注意,在你的情况下,编写this.findViewById(...)并不是真的必要,并且可能被认为是不好的风格。