0

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:

  1. How can I create an array with objects of different classes?
  2. 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();
    }
}

1 Answers1

1

You can use the class Object:

Object[] obj = new Object[3];
obj[0] = new Dog;
obj[1] = new Cat;
obj[2] = new Rat;

As per requested, here is how to retrieve it:

Object objRetrieved = objects[0]; //retrieve the item
String str = null;
if (objRetrieved instanceof String) //Check if its a string
    str = (String) o; //If it is, cast
Luis Fernandez
  • 539
  • 1
  • 4
  • 24
  • How he will catse it if he want to iterate over array ? – Sudhir Ojha Aug 27 '19 at 06:36
  • You'd need to do retrieve it as an Object and do a "instanceof" for every item before doing a cast. It's kinda tiresome and I wouldnt recommend using arrays for storing different types of data but that's what OP asked so... – Luis Fernandez Aug 27 '19 at 06:41
  • yes, i need iterate over array, but the solution to the problem is: obj[1] = new Cat(); Cat cat1 = (Cat)obj[1]; and then cat1.getName(); – Артем Дудник Aug 27 '19 at 07:09