0

I have a scenario that can be best illustrated by the following toy example. Suppose I have four 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 my main routine is

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", but MG.print_nickname() gives me a java.lang.NullPointerException exception. Is there a way for me to fix the constructor or the MG.print_nickname() method to print the nick_name? Thank you.

Feng Mai
  • 2,749
  • 1
  • 28
  • 33
  • Inheritance is like chilli flavoured beer. Sounds nice in theory but usually causes more problems than you expected. Alternatives: Composition. Interfaces (effectively fully abstract base classes) – slipperyseal Mar 17 '15 at 05:32

4 Answers4

3

In inheritance, methods are overridden while fields and static members gets shadowed/hidden.

So If you initialize a field in parent, it will not have any impact on child if you define same field in child as it will get shadowed.

You are not initializing child field which is hiding your parent field and has value null. You need to 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 about shadowing/hiding and overriding : Overriding vs Hiding Java - Confused

Community
  • 1
  • 1
Not a bug
  • 4,286
  • 2
  • 40
  • 80
2

You have forgotten this.the_animal = a_mammal; in Mammal_Groomer's constructor.

Aasmund Eldhuset
  • 37,289
  • 4
  • 68
  • 81
2

You have never initialized the_animal in Mammal_Groomer and hence it is null and thorowing NullPointerException on method invocation. You should initialise it after super call like this:

public Mammal_Groomer(Mammal a_mammal){
    super(a_mammal);
    this.the_animal = a_mammal;
}
Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136
1

the_animal of class Mammal_Groomer has no reference to any Mammal object, resulting in a NULL reference and a NullPointerException.

Falak Dhruve
  • 326
  • 1
  • 10