我有一个包含B类对象的A类,我想从B类中访问A类中的数据。有没有办法访问整数变量' a'来自B级?
public class A{
int a;
B b = new B();
}
public class B{
/*want to access integer variable 'a' in class A from here*/
}
答案 0 :(得分:0)
是的,您所要做的就是将A类传递给B类并将其保存为变量
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);
}
}
但是我会建议使用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());
}
}