I'm trying to figure out whether implementing individual methods of a subclass in an abstract superclass, or casting is the better way to go about the following scenario.
Suppose I have an abstract class Animal
which has two subclasses, Dog
and Cat
and a Main
class where I save objects of Dog
and Cat
in an Animal
array. The following is how I would go about using methods of the subclasses in a more generalized array.
class Main{
public static void main(String[] args){
Animal[] animalArray = new Animal[2];
animalArray[0] = new Cat();
animalArray[1] = new Dog();
for (Animal a : animalArray){
if (a.getClass().equals(Dog.class){
((Dog)a).bark();
} else {
((Cat)a).meow();
}
}
}
}
However a friend suggested that casting isn't best practice, and that I should define each method in the abstract superclass in the following way:
public abstract class Animal{
public abstract String meow(){
return null;
}
public abstract String bark();
return null;
}
}
After setting the return values of these methods to null
I would need to use @Override
and implement them in the respective subclasses.
Which way is better? I'm afraid the abstract class will be too large and will have methods assigned to subclasses that don't make sense (even if all they do is return null
). I think by using casting I can make more precise uses of the methods.
meow()
and bark()
shouldn't be defined in the Animal
class. These methods are specific to Cat
and Dog
classes.
You should define an abstract
method as shown below, in the Animal
class and override
it in the sub classes.
public abstract class Animal {
public abstract String action() {};
}
public class Dog extends Animal {
@Override
public String action() {
//your implementation (bark)
}
}
public class Cat extends Animal {
@Override
public String action() {
//your implementation (meow)
}
}
Hope it answers your query.