简体   繁体   中英

Java- When class A call the classB, in class B how can I use the method and attribute of classA?

I met one problem, I have two class class A and class B they look like:

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();
 // ...
 }
}

How can I keep the value of String s when we call the method a2? And I don't like use b.b1(s) in a2 and a.a2(s) in b1.

Thank you for your suggestions.

You should inject the calling instance of A into b1 :

public b1(A a) {
  ...
}

to avoid needing to create a new A in that method. Then, in a1 , you can call it like:

b.b1(this);

This is known as dependency injection : the working of b1 depends upon an instance of A , so you inject that dependency.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM