我遇到了一个问题,我有两个课程class A
和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
的值?
我不喜欢在a2中使用b.b1(s)
,在b1中使用a.a2(s)
。
感谢您的建议。
答案 0 :(得分:1)
您应该将A
的调用实例注入b1
:
public b1(A a) {
...
}
以避免需要在该方法中创建新的A
。然后,在a1
中,您可以将其称为:
b.b1(this);
这称为dependency injection:b1
的工作取决于A
的实例,因此您注入了该依赖项。