Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Inheritance for beginners

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"?

like image 353
user1870482 Avatar asked Feb 26 '26 01:02

user1870482


2 Answers

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.

like image 171
Marko Topolnik Avatar answered Feb 27 '26 15:02

Marko Topolnik


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.

like image 29
Dims Avatar answered Feb 27 '26 14:02

Dims



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!