简体   繁体   中英

Modifiy method called from extended class

I have three classes, and I need to modify first class through the second that is extended:

my first class A:

public class A{

private String name;

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

my second class B

public abstract class B  {
 public void init() {

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

my third 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

}

expected output, in my third class:

a.Getname = "bar"

you can return a in the init method of B like below.

public A init() {

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

Then you can set the value in C like below

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

Your code has multiple issues:

1) Variable b is never declared.
2) Variable a is private to method init, so you can't access it outside the init method.

So the solution should be like:

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
  }
}

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