Francesco Tronca
Francesco Tronca

Reputation: 59

Java - Avoiding cast using an array of superclass-objects

I have many sub-classes implementing the superclass Animal (Dog, Cat, Mouse, etc)

So I do:

Animal[] arrayOfAnimals = new Animal[100];

I put in it Dog,Cat etc objects.

When I get something from it I do

If(arrayOfAnimals[1] instanceof Dog) {
    ((Dog)(arrayOfAnimals[1])).speak();
}

else if(arrayOfAnimals[1] instanceof Cat) {
    ((Cat)(arrayOfAnimals[1])).speak();
}

Because I need to know if that Animal is a Cat or a Dog because,for example, each one speaks differently.

Now assuming I have many subclasses of Animals, I will consecutively get many "else if..."

My question is: Is there a way to avoid this? I have already tried using an interface (Animal -> interface, Dog,Cat etc implementing animal), but in my project an array has to be cloneable, and you can't clone an array "Animal [] arrayOfAnimals" if Animal is an interface (objects inside that array will not be cloned)

Upvotes: 2

Views: 2041

Answers (2)

Jon Skeet
Jon Skeet

Reputation: 1500225

Because i need to know if that Animal is a Cat or a Dog because,for example, each one speaks differently.

That sounds like it's an implementation detail - if every animal can speak in some form, you should put the speak() method into Animal as an abstract method. Each subclass will then override it to provide the implementation. Then you can just use

arrayOfAnimals[1].speak();

... and polymorphism will take care of using the right implementation.

You can clone an array of an interface type, btw:

interface Foo {
}

class FooImpl implements Foo {
}

public class Test {
    public static void main(String[] args) {
        Foo[] foos = { new FooImpl() };

        Foo[] clone = (Foo[]) foos.clone();
        System.out.println(foos[0] == clone[0]); // true
    }
}

Note that regardless of the type involved, calling clone() on array won't clone each element - the new array will contain the same references as the old array. It's a shallow copy. If you want to do that, you'll have to code it yourself (or find a third party library).

Upvotes: 9

Selim
Selim

Reputation: 1013

Why don't you move speak() to the superclass and let the subclasses override it?

Upvotes: 1

Related Questions