tags:

views:

255

answers:

2

Hi,

What is the use of creating base class object using child class reference in Java

+2  A: 

If I understand correctly, you mean:

class Parent {
   ...
}

class Child extends Parent {
   ...
}

Parent p = new Child ();

There are many reasons:

  1. Flexibility: you can use Parent as a parameter type, and pass any subclass (i.e. Child and other) as this parameter.

  2. Polymorphism: You can override Parent method in several Child classes and use them in turn where Parent object required (like in Strategy pattern)

  3. If you're working on some public API you can make Parent class public and visible to everyone but all Childs can be invisible to outer users. It can make your API more narrow. Good example is Collections API. There are 32 implementations (i.e. Childs) which are used implicitely, but only a few public interfaces. You can obtain synchronized, unmodifiable and other collections through Collection (i.e. Parent) interface not knowing implementation details.

Roman
A: 

If you mean things like

List<String> list = new ArrayList<String>()

then you are not actually creating an instance of the superclass. You are only telling the user to handle it as if it was one. The point is that you often don't need to know the exact implementation that was chosen and wish to retain the ability to change the implementation. Hence you only tell a user of an API that something is a List and if your algorithm requires it, you can change the implementation to use a LinkedList instead, without changing the API.

Confusion