//src/com/test/animal/Animal.java
package com.test.animal;
public class Animal
{
Animal()
{
init();
}
public void init()
{
System.out.println("parent init()");
}
}
//src/com/test/animal/Dog.java
package com.test.animal;
public class Dog extends Animal
{
String name = null;
Dog()
{
super();
}
public void init()
{
System.out.println("child init()");
super.init();
name = new String("dog");
System.out.println("name: "+name);
}
public static void main(String[] args)
{
Dog d = new Dog();
System.out.println("name: "+d.name);
}
}
The output is:
child init()
parent init()
name: dog
name: null
It seems the init() in child is called, but NAME value not saved! Why?
It would be OK if I move NAME to parent. However, it’s more resonable to retain in child, since it’s Dog-specific.
Also, I can explicitly call init() in child’s constructor to solve this issue. It’s not that good.
The order in which this executes is as follows:
Dogconstructor is called.Animalconstructor.Animalconstructor calls theinitmethod. Because it is overridden inDog, theDogversion is called.Dog.inityou setnameto"dog".Dog.initmethod returns.Dogare initialized. This setsnametonull.Result:
namewill benull.An excellent example of why you should not call methods that can be overridden from a constructor – because it leads to surprises like this.
Side note: Never do this:
Just do this instead:
It is never necessary to explicitly create a new
Stringobject from a string literal.