英文:
Can you create an array of objects that are of different classes?
问题
通常情况下,当我们创建一个数组时,我们会指定数组的类型,例如 char [] arrayA = new char [] { 3 }
。但是,在处理对象时,Java是将每个对象视为特定类型,还是将这些数组视为特定类的数组呢?换句话说,我们能否在同一个数组中创建来自不同类的不同对象的数组?
英文:
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?
答案1
得分: 1
如果您创建一个像char []
这样的数组,它只能容纳类型为char
的对象。
如果您想要持有多种不带有相关接口的不同对象类型,您可以使用Object []
来持有对象列表。通过使用(Object)
来进行对象转换。在完成后,将对象转换回其原始类型。
如果您的类实现了相同的接口,您可以使用接口类型的列表来持有对象,以增加清晰度。
interface Listable
class foo implements Listable
class bar implements Listable
Listable[] 可以同时持有foo和bar。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论