public class InheritanceExample {
static public void main(String[] args){
Cat c = new Cat();
System.out.println(c.speak());
You're shadowing the field inherited from Animal
. You have a few options, but the prettiest way of doing it is passing the sound in the constructor:
public class Animal {
private final String sound;
protected Animal(String sound){
if (sound == null)
throw new NullPointerException("sound");
this.sound = sound;
}
public String speak(){
return sound;
}
}
public class Cat extends Animal {
public Cat(){ super("meow"); }
}
public class Dog extends Animal {
public Dog(){ super("woof"); }
}
This way, you can make sure that an Animal
always has a valid sound, right from construction.