public class InheritanceExample {
static public void main(String[] args){
Cat c = new Cat();
System.out.println(c.speak());
You cannot override class fields, only methods. The sound
field in your Dog
and Cat
classes is actually hiding the sound
field in the Animal
superclass.
You can, however, access superclass fields from subclasses, so you could do something like this:
public class Dog extends Animal {
public Dog() {
sound = "woof";
}
}
public class Cat extends Animal {
public Cat() {
sound = "meow";
}
}
Or, you can make the Animal
class abstract, and declare the speak
method abstract too, then define it in subclasses:
public abstract class Animal {
public abstract String speak();
}
public class Dog extends Animal {
public String speak {
return "woof";
}
}
public class Cat extends Animal {
public String speak {
return "meow";
}
}