如何创建具有不同实例的对象数组?

时间:2018-12-22 15:14:37

标签: java arrays class

我有一个具有以下类的Java应用程序:CarPhone。每个类都具有方法connectToBluetooth(),该方法将打印有关该类与蓝牙的连接的消息。

在另一个类中,我想创建一个对象数组,在其中添加已经创建的每个对象的实例。然后,我想访问与每个实例相对应的connectToBluetooth方法。我为每个类创建了一个实例:

我想创建这两个实例的数组,并访问对应于每个类的connectToBluetooth方法。 (构造函数要求所有者和设备的颜色)

    Car car = new Car("John", "red");
    car.connectToBluetooth();

    Phone phone = new Phone("Susan","black");
    phone.connectToBluetooth();

3 个答案:

答案 0 :(得分:2)

Object [] arr =新的Object []

您可以使用Object数组,但是在这种情况下,您必须在调用connectToBluetooth()之前先设置具体实例:

Object[] arr = { new Car("John", "red"), new Phone("Susan","black") };

for (Object obj : arr) {
    if (obj instance of Car)
        ((Car)obj).connectToBluetooth();
    else if (obj instance of Phone)
        ((Phone)obj).connectToBluetooth();
}

Bluetooth [] arr =新的Bluetooth []

更正确的方法是使用connectToBluetooth()方法声明一个接口并将其用作数组类型:

interface Bluetooth {
    void connectToBluetooth();
}

class Car implements Bluetooth {} 
class Phone implements Bluetooth {}

Bluetooth[] arr = { new Car("John", "red"), new Phone("Susan","black") };

for (Bluetooth bluetooth : arr)
    bluetooth.connectToBluetooth();

答案 1 :(得分:1)

您可以创建一个Objects数组,以便在其中添加两种Object类型,但这不是一个好方法。更好的方法是为PhoneCar创建一个超级类型,并创建一个该类型的数组(超级类型可以是接口或类)。

例如,创建一个名为class的{​​{1}}并将该类扩展到Phone和Car。然后创建一个BlueToothDevice类型的数组,并将它们都添加。

答案 2 :(得分:1)

这是实际的解决方案,其中蓝牙是实现的接口:

Bluetooth[] bluetooth= new Bluetooth[2];
bluetooth[0] = new Car("John", "blue"); 
bluetooth[0].connectToBluetooth(); //-> prints message coresponding to Car class 
bluetooth[1] = new Phone("Susan", "black");
bluetooth[1].connectToBluetooth(); //-> prints message coresponding to Phone class