user8174370
user8174370

Reputation:

An array for different objects in java?

So, for example, let's say I have this class named for example "Animals", a subclass called "Dogs" and other one called "Cats" and a class for running the program.

class Animals{
    int size;
    String name;
}
class Dogs extends Animals{
    void bark(){
        System.out.println("Woff");
    }
}

class Cats extends Animals{
    void meow(){
        System.out.println("Meow");
    }
}

And in the class Test I want to create an array that holds both of them. How should I declare them so I can also access to their methods? I was thinking, for example, in something like this:

class Test{
    public static void main(String[] args){
        Animals [] array = new Animals[2];
        array[0] = new Dogs();
        array[1] = new Cats();
        array[0].bark();
    }
}

But it doesn't seem to work that way since Java recognizes the method as a Animals' method.

Upvotes: 1

Views: 1611

Answers (3)

jrtapsell
jrtapsell

Reputation: 6991

Why doesn't this work

As the array is of animals it won't let you call the subclasses methods, as the compiler can't be sure any animal would have a bark or meow method.

How to fix

You can do one of the following:

  • Add an abstract makeSound method to animal, and use for both, so the compiler knows the method exists.
  • Have 2 arrays, 1 of dogs and one of cats, so the compiler knows the method exists.
  • Check the types of each item using instanceof and call the methods after casting to the right type, so the type is checked at runtime.

Upvotes: 1

buettner123
buettner123

Reputation: 414

You can ask for the instance of the object at the array position and after this it's safe to call the method by casting the object to the dogs class:

if(array[0] instanceof Dogs) {
    ((Dogs)array[0]).bark()
}

Upvotes: 0

azro
azro

Reputation: 54148

You need to use instanceof to check wether the animal is a cat or a dog, then safe cast and call the good method :

public static void main(String[] args){
    Animals [] array = new Animals[2];
    array[0] = new Dogs();
    array[1] = new Cats();
    array[0].bark();
}

public static void makeSound(Animal[] animals){
    for(Animal a : animals){
        if(a instanceof Dogs){
            ((Dogs)a).bark();
        }else if(a instanceof Cats){
            ((Cats)a).meow();
        }
}

This will print :

Woff
Meow

Better practice :

class Animals{
    int size;
    String name;
    abstract void makeSound();
}
class Dogs extends Animals{
    void makeSound(){
        System.out.println("Woff");
    }
}

class Cats extends Animals{
    void makeSound(){
        System.out.println("Meow");
    }
}

Upvotes: 1

Related Questions