-2

What is benefit to create a object using super class reference?

like

class People{
}
class Child extends People{
}
public class Demo{
public static void main(String []){
People p=new Child();      //line 1
Child d=new Child();       //line 2
}

}

I just want to know actual use of this line 1 and line 2.

chintan
  • 471
  • 3
  • 16

2 Answers2

4

List l can refer to any object of its implementation like ArrayList,LinkedList etc. With the first approach :

List l=new ArrayList();

You can change the implementation later without affecting the code which references it.

List l=new LinkedList();

This is called coding to an interface , not implementation. It is in accordance to Liskov Substitution Principle. Code to an interface when you know or anticipate change and/or different implementation.

The only reason I can consider declaring it as

ArrayList ar=new ArrayList();

When I am sure that the implementation will not change in future ( but remember , change is the only constant ) and I want to use ArrayList specific methods in my code which are not defined in the List interface, and you don't want to use a cast like :

List list = new ArrayList();
((ArrayList) list).trimToSize();
AllTooSir
  • 48,828
  • 16
  • 130
  • 164
1

What is benefit to create a object using super class reference?

The main benefit is you can hold the object of any of its subclasses. There are situations where you don' know what object you will get at run time but you are sure that you will get an object of a Parent class or any of its subclasses. This can reduce the size of code and number of methods you will write.

Juned Ahsan
  • 67,789
  • 12
  • 98
  • 136