Inheritance.java
public class InheritanceExample {
static public void main(String[] args){
Cat c = new Cat();
System.out.println(c.speak());
Dog d = new Dog();
System.out.println(d.speak());
}
}
Animal.java
public class Animal {
protected String sound;
public String speak(){
return sound;
}
}
Cat.java
public class Cat extends Animal {
protected String sound = "meow";
}
Dog.java
public class Dog extends Animal {
protected String sound = "woof";
}
Output:
null
null
My animals cannot speak. So sad.
A method will look in its own class' namespace to resolve fields. While methods defined in sub-classes can look up the hierarchy to resolve fields, the same is not true for classes defined higher up in the hierarchy, i.e., super-classes won't look down the hierarchy to resolve fields [and their values]