Java-当A类调用classB时,在B类中如何使用classA的方法和属性?

时间:2016-04-17 20:55:13

标签: java

我遇到了一个问题,我有两个课程class Aclass 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)

感谢您的建议。

1 个答案:

答案 0 :(得分:1)

您应该将A的调用实例注入b1

public b1(A a) {
  ...
}

以避免需要在该方法中创建新的A。然后,在a1中,您可以将其称为:

b.b1(this);

这称为dependency injectionb1的工作取决于A的实例,因此您注入了该依赖项。