Satyaki Kundu
Satyaki Kundu

Reputation: 25

Why do we use Parent Class reference for overriding in Java?

class Father {
    void name() {
        System.out.println("This is father");
    }

    void details() {
        System.out.println("He is the head of the family");
    }

    void traits() {
        System.out.println("He loves everyone");
    }
}

class Son extends Father {
    @Override
    void name() {
        System.out.println("This is the son");
    }

    @Override
    void details() {
        System.out.println("He is the youngest one in the family");
    }
}


public class overridingDoubt {
    public static void main(String... args) {

        System.out.println("Father type ref");
        System.out.println("******************");
        Father obj = new Son();//This raises my doubt
        obj.name();
        obj.details();
        obj.traits();

        System.out.println("\n \n Son type ref");
        System.out.println("******************");
        Son obj1 = new Son();
        obj1.name();
        obj.details();
        obj.traits();       
    }
}

Both the references are achieving the same results too. I just want to know a real life scenario where using Parent class reference is of utmost importance.

I've been told a scenario where we would want to store all the objects in a List and using Parent class reference would let us achieve that.

Upvotes: 0

Views: 80

Answers (1)

Expired Data
Expired Data

Reputation: 678

If you want to store the items using generics, or if you want to define a Type which may be any child class, depending on the code. If you want to check that all objects are an instanceof a given parent class etc.

E.g. If you simply want a list of people, who can be any class extending Person you can have

List<Person> list = new ArrayList<Person>(); 

Then in your code say you want to have a father and two sons, who each extend Person you can add these to the list

list.add(new Father()); //Etc. 

Then you could for example iterate through the list printing the details.

for(Person p: list){
    p.details();
}

Upvotes: 2

Related Questions