-1

Hello I have the following code that gives me a NullPointerException when I call the function child.any() Why this happens and how to solve this?

public main {
  public void main(String[] args) {
    Parent parent = new Parent();
    Child child = new Child();
    Tmp tmp = new Tmp();
    parent.setter(tmp);
    child.any();
  }
}

public Parent {
  Tmp tmp;
  protected void setter (Tmp tmp) {
    this.tmp = tmp;
  }
}

public Child extends Parent {
  protected void any() {
    tmp.printTmp();
  }
}

public Tmp {
  public void printTmp() { 
    System.out.println("Hello");
  }
}
Blue Fire
  • 29
  • 8
  • @user16320675 so I will need to send objects to each child class as I did with the parent? – Blue Fire Sep 22 '21 at 17:46
  • Please clarify your specific problem or provide additional details to highlight exactly what you need. As it's currently written, it's hard to tell exactly what you're asking. – Community Sep 29 '21 at 20:56

1 Answers1

0

Have a setter in the child class also.
In your case parent and child are two different objects

public class Main {
    public static void main(String[] args) {
        Parent parent = new Parent();
        Child child = new Child();
        Tmp tmp = new Tmp();
        parent.setter(tmp);
        child.setter(tmp);
        child.any();
    }
}

class Parent {
    Tmp tmp;

    protected void setter(Tmp tmp) {
        this.tmp = tmp;
    }
}

class Child extends Parent {
    protected void any() {
        tmp.printTmp();
    }
    
    protected void setter(Tmp tmp) {
        this.tmp = tmp;
    }
}

class Tmp {
    public void printTmp() {
        System.out.println("Hello");
    }
}

Good read

https://docs.oracle.com/javase/8/docs/api/java/util/Objects.html https://stackoverflow.com/questions/40480/is-java-pass-by-reference-or-pass-by-value

Sreyas
  • 744
  • 1
  • 7
  • 25