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"?
To avoid confusion, be sure to understand that the subclass object you create always contains all the methods. Downcasting is a no-op; you just treat the very same object as an instance of the subtype.
Corollary: you can never change the behavior of an object by downcasting. It directly follows from this that you always access the same overriding method and never a method from the superclass.
This kind of behavior allows you to substitute different behaviors for the same declared supertype. It's called polymorphism and is the workhorse of Java programming, and OOP in general. Without it there would be no point in having a class hierarchy in the first place. At least, it would be much, much less useful.
You can imagine inheritance as creating hidden member named super.
Each object instance in Java has it's own constant type. You don't change it while casting. While casting you just say to Java that you are sure this object is of subtype.
Overrided methods remain overriden, this is Java's ideology. If you know C++, you can say that all functions in Java are virtual.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With