-2

I just found this pretty intriguing. Usually when we make an array we specify the type of the array ie. char [] arrayA = new char [] { 3 }. But, when dealing with objects, does Java treat each as a specific type, or does it treat these arrays from the specific classes? In other words, can we make an array of different objects from different classes in the same array?

4
  • 1
    Why dont you try it? Commented Sep 27, 2020 at 18:35
  • I would try but I'm not sure how exactly to do so. Commented Sep 27, 2020 at 18:36
  • 4
    Does this answer your question? Java Array with multiple data types Commented Sep 27, 2020 at 18:36
  • Thank you, I'll see if it works. Commented Sep 27, 2020 at 18:37

1 Answer 1

1

If you make an array like char [], it can only hold objects typed char.

If you would like to hold multiple different Object types with no related Interface you can use Object [] to hold a list of Objects. Cast the object by using (Object). Cast the object back to its original type when done.

If your classes implement the same interface you can use a list of the interface type to hold the objects for more clarity.

Interface Listable

foo implements Listable

bar implements Listable

Listable [] can hold both foo and bar.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.