簡體   English   中英

從擴展 class 調用的修改方法

[英]Modifiy method called from extended class

我有三個類,我需要通過擴展的第二個修改第一個 class:

我的第一個 class A:

public class A{

private String name;

public void setName(String name) {
        this.name= name;
    }

我的第二個 class B

public abstract class B  {
 public void init() {

   A a = new A();
  a.setHost("foo"); 
 }
}

我的第三個 class C

public class C extends B {
// I want to use the method setName() of the a declared in class B
  b.init.a.setName("bar");//compile error, I tried several syntax I don't know how to do it

}

預計 output,在我的第三個 class 中:

a.Getname = "bar"

您可以在 B 的 init 方法中返回 a ,如下所示。

public A init() {

  A a = new A();
  a.setHost("foo"); 
  return a;
 }

然后你可以在 C 中設置值,如下所示

public class C extends B {
   public setNameinA() {
      B b = new B();
      b.init().setName("bar");
   }
}

您的代碼有多個問題:

1) 變量 b 從未被聲明過。
2) 變量 a 是方法 init 的私有變量,因此您不能在 init 方法之外訪問它。

所以解決方案應該是這樣的:

Class B:

public abstract class B  {

 protected static A a = new A(); // Protected to make it visible to child class
 public void init() {

  a.setHost("foo"); 
 }
}

Class C:

public class C extends B {
  public static void main(String[] args) {
    a.setName("bar");
    System.out.println(a.getName());  //Output = bar
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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