簡體   English   中英

Java-當類A調用類B時,在類B中如何使用類A的方法和屬性?

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

我遇到了一個問題,我有兩個class A class Bclass 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM