java this:作为参数传递给方法
this
关键字也可以作为方法中的参数传递。 它主要用于事件处理。 看看下面的一个例子:(更多教程请阅读码农之家)
class S2 {
void m(S2 obj) {
System.out.println("method is invoked");
}
void p() {
m(this);
}
public static void main(String args[]) {
S2 s1 = new S2();
s1.p();
}
}
执行上面代码输出结果如下 -
method is invoked
这个应用程序可以作为参数传递:
在事件处理(或)的情况下,必须提供一个类的引用到另一个。 它用于在多个方法中重用一个对象。
this:在构造函数调用中作为参数传递
也可以在构造函数中传递this
关键字。 如果必须在多个类中使用一个对象,可以使用这种方式。 看看下面的一个例子:
class B {
A4 obj;
B(A4 obj) {
this.obj = obj;
}
void display() {
System.out.println(obj.data);// using data member of A4 class
}
}
class A4 {
int data = 10;
A4() {
B b = new B(this);
b.display();
}
public static void main(String args[]) {
A4 a = new A4();
}
}
执行上面代码输出结果如下 -
10