I have a class A and within class AI have function func1
and func2
. In the same file I have class B and in that class BI have function func3
. In the main class, an object obj1
of class A
is declared. With this object, func1
of class A
is called. Within func1
of class A
, an object obj2
of class B
is created. With this object, func3
of class B
is called. Now within func3
of class B
, i want call func2
of class A
with the object obj1
. For this I want to refer to that object from within func3
of class B
. Is it possible? If yes, how?
I tried using this.this.func2
which wouldn't work. For now I am passing the object obj1
as an argument and it works fine. But I want to do the same without passing it because I want to use an array of objects and every time the object should differ
class A {
int attr1, attr2;
public void func1() {
int attr1 = 3;
int attr2 = 6;
B obj2 = new B();
obj2.func3();
}
public void func2() {
this.attr1 = 5;
this.attr2 = 10;
}
}
class B {
int atr1, atr2;
public void func3() {
atr1 = 4;
atr2 = 8;
// here I want to access the object obj1 to call the function func2()
}
}
public class Main {
public static void main(String args[]) {
A obj1 = new A();
A.func1();
}
}
Is it possible?
Yes.
If yes, how?
Option 1: Pass as parameter
Pass obj1
as parameter to func3
.
Or more precisely, since func3
is called from a method of obj1
, pass this
as the parameter value:
class A {
public void func1()
{
B obj2 = new B();
obj2.func3(this);
}
}
class B {
public void func3(A a)
{
a.func2();
}
}
Option 2: Pass to constructor
Pass the A
reference to the B
constructor, and have B
remember it in a field.
class A {
public void func1()
{
B obj2 = new B(this);
obj2.func3();
}
}
class B {
A a;
public B(A a) {
this.a = a;
}
public void func3()
{
this.a.func2();
}
}
Option 3: Inner class
Make class B
an inner class of A
. Essentially the same as option 2, but the compiler handles the reference to A
for you.
class A {
public void func1()
{
B obj2 = new B();
obj2.func3();
}
class B {
public void func3()
{
A.this.func2();
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.