java - NullPointerException when using inheritence -
i have scenario can best illustrated following toy example. suppose have 4 classes:
public class animal { public animal(string a_name){ this.name = a_name; } public string name; } public class mammal extends animal{ public mammal(string a_name, string a_nickname) { super(a_name); this.nick_name = a_nickname; } string nick_name; } public class animal_groomer{ public animal_groomer(animal an_animal){ this.the_animal = an_animal; } public void print_name() { system.out.println(the_animal.name); } public animal the_animal; } public class mammal_groomer extends animal_groomer{ public mammal_groomer(mammal a_mammal){ super(a_mammal); } public void print_nickname(){ system.out.println(the_animal.nick_name); } public mammal the_animal; }
now if main routine
mammal a_mammal = new mammal("tiger", "bob"); mammal_groomer mg = new mammal_groomer(a_mammal); mg.print_name(); mg.print_nickname();
mg.print_name() outputs "tiger", mg.print_nickname() gives me java.lang.nullpointerexception exception. there way me fix constructor or mg.print_nickname() method print nick_name? thank you.
in inheritance, methods overridden while fields , static members gets shadowed/hidden.
so if initialize field in parent, not have impact on child if define same field in child shadowed.
you not initializing child field hiding parent field , has value null
. need initialize member of child class separately in child constructor.
public mammal_groomer(mammal a_mammal){ super(a_mammal); this.the_animal = a_mammal; }
read more shadowing/hiding , overriding : overriding vs hiding java - confused
Comments
Post a Comment