Calling a parent method in a child class returns a null value

  • A+
Category:Languages

I'm trying to display the value of a variable from the parent class by using a parent method but from within a child class.

public class A {     public static void main(String[] args) {         Parent p1 = new Parent();         p1.input();     } } class Parent {     private String name;     public void setName(String newName) {         name = newName;     }     public String getName() {         return name;     }     public void input() {         String q = "hi";         setName(q);         Child c1 = new Child();         c1.input();     } } class Child extends Parent {     public void input() {         System.out.print(super.getName());     } } 

I was expecting it to output hi but instead the output is null. Things I've tried:

  1. Using getName() instead of super.getName() in the child class.
  2. Using Parent p2 = new Parent(); and then p2.getName() in the child class.
  3. Using protected String name; in the parent class.

None of these seem to work; all of them still output null in the end. Help?

 


You're creating a Child object within a Parent object, and you're setting the current parent object's name field, but not the Parent of the Child, meaning you've more than one Parent object being created -- one whose name field is being set, and the other (the parent of the child) whose name field is never set, but is tested.

As a side bit, a Parent class should not be doing this sort of thing. It should be child "agnostic".

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: