Home > Mobile >  Object not changed in the parent classes Java
Object not changed in the parent classes Java

Time:09-23

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");
  }
}

CodePudding user response:

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

  • Related