![](/img/trans.png)
[英]How can I access a Local Variable which is an object from within another class? - Java
[英]access a class variable from within an object in that class in java
我有一個類A,其中包含來自類B的對象,並且我想從類B內訪問類A中的數據。有沒有辦法從類B內訪問整數變量“ a”?
public class A{
int a;
B b = new B();
}
public class B{
/*want to access integer variable 'a' in class A from here*/
}
是的,您要做的就是將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);
}
}
但是我建議使用吸氣劑
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());
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.