这是什么意思?
可能重复:
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);
另外,为什么在这个例子中没有使用Button定义按钮但是使用View,有什么区别?
PS。 很棒的网站! 试着学习java并在这里搜索得到各种答案!
this
关键字是对当前对象的引用 。 它用于传递对象的这个实例,等等。
例如,这两个分配是相同的:
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); } }
在最后一个示例中,您将当前对象的引用传递给静态方法。
另外,为什么在这个例子中没有使用Button定义按钮但是使用View,有什么区别?
在Android SDK中, Button
是View
的子类 。 您可以将Button
作为View
请求并将View
转换为Button
:
Button newButton = (Button) this.findViewById(R.id.new_button);
this
是指正在采取行动的对象的实例。
在你有上面的情况下, this.findViewById(R.id.continue_button)
这是指父类中的一个方法(具体是Activity.findViewById()
或View.findViewByid()
,假设你正在编写自己的子类Activity
或View
!)。
this
指的是一个类的当前实例
this
在Java中是对当前对象实例的引用。 因此,如果您正在为MyClass
类编写方法,那么this
是MyClass
的当前实例。
请注意,在您的情况下,写入this.findViewById(...)
并不是必需的,并且可能被视为不良风格。
面向对象语言(如java)中的“this”,c#是对要调用方法的对象或要访问其数据的对象的引用。
看看这个链接是否有助于您理解“这个”更多 –
http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html
“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. } }