Sobes.tech
Junior — Middle

How to implement adding three different class objects into one array?

sobes.tech AI

Answer from AI

In Java, to store objects of different classes in a single array, you can use an array of type Object[], since all classes inherit from Object.

Example:

class A {}
class B {}
class C {}

public class Main {
    public static void main(String[] args) {
        Object[] arr = new Object[3];
        arr[0] = new A();
        arr[1] = new B();
        arr[2] = new C();

        for (Object obj : arr) {
            System.out.println(obj.getClass().getSimpleName());
        }
    }
}

If classes are related by a common hierarchy, it is better to use an array or collection of that common type for more type-safe code.

How to implement adding three different class objects… - sobes.tech