Reputation:
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
Reputation: 6991
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.
You can do one of the following:
Upvotes: 1
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
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