Reputation: 101
Consider the following. You have a Dog Class and a Cat Class, that both extend the Class Animal. If you create an array of Animals Eg.
Animal[] animals = new Animal[5];
In this array 5 random Cats and Dogs are set to each element.
If the Dog Class contains the method bark()
and the Cat Class does not, how would this method be called in terms of the array? Eg.
animals[3].bark();
Iv'e tried to cast the element, I was examining to a Dog but to no avail Eg.
(Dog(animals[3])).bark();
Upvotes: 0
Views: 105
Reputation: 159086
Option 1: Use instanceof
(not recommended):
if (animals[3] instanceof Dog) {
((Dog)animals[3]).bark();
}
Option 2: Enhance Animal
with abstract method:
public abstract class Animal {
// other stuff here
public abstract void makeSound();
}
public class Dog extends Animal {
// other stuff here
@Override
public void makeSound() {
bark();
}
private void bark() {
// bark here
}
}
public class Cat extends Animal {
// other stuff here
@Override
public void makeSound() {
meow();
}
private void meow() {
// meow here
}
}
Upvotes: 1