i have class A containing an object from class B and i want to access the data in class A from within class B. is there a way to access integer variable 'a' from within class B?
public class A{
int a;
B b = new B();
}
public class B{
/*want to access integer variable 'a' in class A from here*/
}
Yes all you have to do is pass class A to class B and save it as a variable
public class A{
int myNumb = 5;
B b = new B(this);
}
public class B{
A a;
public B (A a){
this.a=a;
test();
}
public void test(){
System.out.println(a.myNumb);
}
}
However I would recomend using getter
public class A{
int myNumb = 5;
B b = new B(this);
public int getmyNumb(){
return myNumb;
}
}
public class B{
A a;
public B (A a){
this.a=a;
test();
}
public void test(){
System.out.println(a.getmyNumb());
}
}
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.