I'm trying to wrap my head around inheritance in java. So far I understood that if i declare an object in the following fashion: Superclass object = new Subclass() the created child object is restricted to the methods of the parent object. If I want to access the additional methods of the child i would have to cast to the child.
But why are methods still overridden in the child class.
Here's my example
public class Parent {
public Parent() {
}
public void whoAmI(){
System.out.println("I'm a parent");
}
}
public class Child extends Parent {
public Child() {
}
public void whoAmI(){
System.out.println("I'm a child");
}
public void childMethode() {
System.out.println("Foo");
}
}
public class Test {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
List<Parent> list = new ArrayList<>();
Child c = new Child();
Parent p = new Parent();
Parent pc = new Child();
c.whoAmI();
p.whoAmI();
pc.whoAmI();
// Access child methodess
((Child) pc).childMethode();
list.add(c);
list.add(p);
list.add(pc);
System.out.println(list.size());
}
}
pc.whoAmI() prints "I'm a child". Why doesn't it print "I'm a parent"?