Iuli
Iuli

Reputation: 31

How to create an array of objects with different instances?

I have a java app which has the following classes: Car and Phone. Each class has the method connectToBluetooth(), which prints a message regarding the class' connection to bluetooth.

In another class, I want to create an array of objects in which I add the instances of each one of the objects already created. Then, I want to access the connectToBluetooth method coresponding to each instance. I have created one instance for each class:

I want to create an array of these two instances and to access the connectToBluetooth method coresponding to each class. (The constructors ask for the owner and the device's color )

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

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

Upvotes: 0

Views: 1577

Answers (3)

Oleg Cherednik
Oleg Cherednik

Reputation: 18245

Object[] arr = new Object[]

You could use array of Object, but in this case you have to case concrete instance before invoke 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 = new Bluetooth[]

More correct way is to declare an interace with connectToBluetooth() method and use it as array type:

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();

Upvotes: 2

Iuli
Iuli

Reputation: 31

This is the actual solution, where Bluetooth is the interface implemented:

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

Upvotes: 1

Sandeepa
Sandeepa

Reputation: 3755

You can create an array of Objects for where you can add both Object types to it which is not a good way. The better way is to create a super type for Phone and Car and create a array of that Type (super type can be an interface or a class).

For an example create a class called BlueToothDevice and extend that class to both Phone and Car. Then create an array of BlueToothDevice type and add both of them.

Upvotes: 1

Related Questions