Java Array存储具有多个字段的对象

时间:2015-06-11 08:21:12

标签: java

我的公共类工具包含两个子类CarTruck,每个子类都扩展Vehicle。每个类的构造函数与3个字段相同,颜色,品牌和汽油里程。

我已经声明了一个数组

Vehicle [] vehArray = new Vehicle[6];

将存储6种不同的车辆。我知道一个电话

Car car1 = new Car("Red", "Ford", 15); 

将使用car1类型的对象实例化Car

如何将car1存储在vehArray[0]

5 个答案:

答案 0 :(得分:3)

尝试做这样的事情:

vehArray[0] = car1;

答案 1 :(得分:0)

最短的方式是:

vehArray [0] = new Car("Red", "Ford", 15);

答案 2 :(得分:0)

甚至

Vehicle[] vehArray = new Vehicle[]{new Car("Red", "Ford", 15), new Truck("Silver", "Mercedes", 2)};

答案 3 :(得分:0)

如下;

1)Test.java;

public class Test {

    public static void main(String[] args) {

        //Array Initialization with null Vehicle placeholders
        Vehicle[] vehicleArray = new Vehicle[6];

        //Car class object instances are assiged
        for( int i = 0; i < vehicleArray.length; i++ )
            vehicleArray[i] = new Car("Red", "Ford", 15+i);

        for( int i = 0; i < vehicleArray.length; i++ )
            System.out.println
                (
                    i + 
                    " : " + vehicleArray[i].getColor() + 
                    " : " + vehicleArray[i].getBrand() + 
                    " : " + vehicleArray[i].getGasMilage()
                );
    }

}

2)Vehicle.java

public class Vehicle {

    private String color;
    private String brand;
    private int gasMilage;

    public Vehicle() {}

    //Constructor with fields
    public Vehicle(String color, String brand, int gasMilage) {
        this.color = color;
        this.brand = brand;
        this.gasMilage = gasMilage;
    }

    public String getColor() {
        return color;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public int getGasMilage() {
        return gasMilage;
    }

    public void setGasMilage(int gasMilage) {
        this.gasMilage = gasMilage;
    }

}

3)Car.java

public class Car extends Vehicle {

    //no-arg constructor
    public Car() {
        super();
    }

    //field constructor
    public Car(String color, String brand, int gasMilage) {
        super(color, brand, gasMilage);
    }

}

4)Truck.java

public class Truck extends Vehicle {

    //no-arg constructor
    public Truck() {
        super();
    }

    //field constructor
    public Truck(String color, String brand, int gasMilage) {
        super(color, brand, gasMilage);
    }

}

答案 4 :(得分:0)

我建议先声明子类的所有对象,然后将其存储在车辆中,如下所示:

Vehicle[] vehicleArray = {ob1,ob2,ob3,ob4,andSo_On};