我遇到了一个问题,我有两个类 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)
。
感谢您的建议。
最佳答案
您应该将 A
的调用实例注入(inject)到 b1
中:
public b1(A a) {
...
}
以避免需要在该方法中创建新的A
。然后,在 a1
中,您可以这样调用它:
b.b1(this);
这被称为 dependency injection :b1
的工作取决于 A
的实例,因此您可以注入(inject)该依赖项。
关于Java-当类A调用类B时,在类B中如何使用类A的方法和属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36682118/