Question

Why would we want to say Base b=new Derived() versus Derived b=new Derived()? As far as I know (correct me if I'm wrong) if we do the latter we could still add it to an arrayList<Base>, right?

Was it helpful?

Solution

This is a problem I recently had to deal with.

Let's say I have a parent class Enemy with child classes EnemyBlob and EnemyBat. Now lets say I want to store all of the enemies in an ArrayList. If I try to do ArrayList<EnemyBat> then I'll need a seperate ArrayList for each type of Enemy.

However, if I use ArrayList<Enemy> then I can add both EnemyBlob's and EnemyBat's to it.

In addition, this lets you use different types of objects.

ArrayList is a subclass of List. If you define all the places you define a list as ArrayLists, then if you get a different type of List (for example to a CopyOnWriteArrayList) then you won't be able to use it.

Basically Polymorphism gives you flexibily to use and override classes.

OTHER TIPS

There's no difference between these:

Base b = new Derived();
list.add(b);

// or

Derived b = new Derived();
list.add(b);

so use whichever you prefer.

There is a difference in other cases - here are some examples:

// this works fine
Base b;
if(randomNumber > 5)
    b = new Derived1();
else
    b = new Derived2();

// this does not compile
Derived1 b;
if(randomNumber > 5)
    b = new Derived1();
else
    b = new Derived2();

// this also works fine, but if you change Base to Derived1 it will not compile
void foo(Base b) {
    System.out.println("Type is "+b.getClass().getName());
}
void bar() {
    foo(new Derived1());
    foo(new Derived2());
}

You're right, but declaring an array list as taking Base instead, will permit to store Base, Derived and all their child.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top