如何创建另一个类的实例,使用数据加载对象并将其打印出来?

时间:2014-12-08 02:43:18

标签: java constructor instance setter getter

我是一个完整的菜鸟(第5天编程),这解释了为什么我花费了无数时间来试图解决这个问题而仍然没有想到它:

如何创建CarAndBikes实例,加载3辆车的信息并将其打印出来?

这是我不完整的代码,可以让您了解问题:

    public class Vehicle {

        String manufacturer, model;
        int numberOfWheels;

        public Vehicle(String manufacturer, String model, int numberOfWheels) {

            this.manufacturer = manufacturer;
            this.model = model;
            this.numberOfWheels = numberOfWheels;
        }

        public String getManufacturer() {
            return manufacturer;
        }

        public String getModel() {
            return model;
        }

        public int getNumberOfWheels() {
            return numberOfWheels;
        }

        public String toString() {
            return "(" + numberOfWheels +") '" + manufacturer + ", " + model + "'";
        }
    }

    public class CarAndBikes {

        private Vehicle[] items;
        private int nextFreeItem = 0;

        CarAndBikes (int size) {
            items = new Vehicle[size];

            for(int i = 0; i < size; i++)
            items[i] = new Vehicle(manufacturer, model, numberOfWheels);
        }

        void addVehicle(String man, String mdl, int wheels) {
            items[nextFreeItem++].addVehicle(man, mdl, wheels);
        }

        public String toString() {
            return "(" + items + ")";
        }
    }

public class TestProgram extends CarAndBikes{
    TestProgram(int size) {
        super(size);
    }

    public static void main(String[] args) {
        Vehicle vehicle1 = new Vehicle("Seat", "Ibiza", 4);
        Vehicle vehicle2 = new Vehicle("Reliant", "Robin", 3);
        Vehicle vehicle3 = new Vehicle("Honda", "Fireblade", 2);

        System.out.println(vehicle1);
        System.out.println(vehicle2);
        System.out.println(vehicle3);
    }
}

2 个答案:

答案 0 :(得分:1)

在我看来,你最好将汽车和自行车分开,将汽车和自行车分成两个单独的类别&#39; Car&#39;和&#39; Bike&#39;然后创建一个第三类来容纳这些对象的集合,这样你就可以使用List或ArrayList来存储它们,并有一个方法来打印它们。

import java.util.ArrayList;

Public Class Garage
{
   private ArrayList<Vehicle> vehicles;

   Public Garage()
   {
     vehicles = new ArrayList<Vehicle>();
   }

   public void addVehicle(Vehicle v)
   {
      vehicles.add(v);
   }

   public void getVehicles()
   {
     for(Vehicle v : vehicles)
     {
       System.out.Println(v.getModel());
     }
   }
}

您会注意到ArrayList接受车辆类型的物体,汽车和自行车都会延伸车辆以便接受它们。

答案 1 :(得分:1)

我注意到toString()中的CarAndBikes方法在数组引用上使用toString()(并且数组不会覆盖toString())。您可以使用Arrays.toString(Object[])之类的

public String toString() {
    // return "(" + items + ")";
    return Arrays.toString(items);
}

您获得的Object.toString()记录为

  

toString的{​​{1}}方法返回一个字符串,该字符串由对象为实例的类的名称,符号字符“@&#39;”和无符号字符组成。对象哈希码的十六进制表示。换句话说,此方法返回一个等于值的字符串:

Object