我有一个具有以下类的Java应用程序:Car
和Phone
。每个类都具有方法connectToBluetooth()
,该方法将打印有关该类与蓝牙的连接的消息。
在另一个类中,我想创建一个对象数组,在其中添加已经创建的每个对象的实例。然后,我想访问与每个实例相对应的connectToBluetooth
方法。我为每个类创建了一个实例:
我想创建这两个实例的数组,并访问对应于每个类的connectToBluetooth
方法。 (构造函数要求所有者和设备的颜色)
Car car = new Car("John", "red");
car.connectToBluetooth();
Phone phone = new Phone("Susan","black");
phone.connectToBluetooth();
答案 0 :(得分:2)
您可以使用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();
}
更正确的方法是使用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
类型,但这不是一个好方法。更好的方法是为Phone
和Car
创建一个超级类型,并创建一个该类型的数组(超级类型可以是接口或类)。
例如,创建一个名为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