![](/img/trans.png)
[英]Class A instantiates a Class B instance. How can the Instance of ClassB call a method of class A?
[英]Java- When class A call the classB, in class B how can I use the method and attribute of classA?
我遇到了一個問題,我有兩個class A
class B
和class B
它們看起來像:
class A{
private String s;
public a1(){
// do something with s
B b = new B();
b.b1();
// do others things
}
public a2(){
// this needs s which has been initialised in method a1
}
}
class B{
public b1(){
// do something
// here, how can I call method a2 and use String s in a2?
A a = new A();
a.a2();
// ...
}
}
當我們調用方法a2時,如何保持String s
值? 而且我不喜歡使用b.b1(s)
在A2和a.a2(s)
在B1。
謝謝你的建議。
您應該將A
的調用實例注入b1
:
public b1(A a) {
...
}
以避免需要在該方法中創建新的A
然后,在a1
,您可以像這樣調用它:
b.b1(this);
這稱為依賴注入 : b1
的工作取決於A
的實例,因此您可以注入該依賴。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.