I have some classes: class Dog, class Cat, class Rat, that are not extended by the superclass. And they have default constructor and some methods, like getName(), getAge().
In the main class I need to create Array with random animals and be able to call any of the animal methods.
So I have a few questions:
- How can I create an array with objects of different classes?
- How do I call the methods of these objects from an array?
I realized that the array contains links, not objects. It turns out through links I cannot get access to methods at objects?
class Dog{
//some code
public getName(){
return this.name;
}
}
class Car{
//some code
public getName(){
return this.name;
}
}
class Rat{
//some code
public getName(){
return this.name;
}
}
public class Test {
public static void main(String[] args) {
//array with some type code
SomeType[] arr = new SomeType[3];
arr[0] = new Dog;
arr[1] = new Cat;
arr[2] = new Rat;
//call method from arr object dont work
arr[0].getName();
}
}