![](/img/trans.png)
[英]How do I create an object in another class when the parameter is out of scope?
[英]How do I create an instance of another class, load an object with data and print it out?
我是一个完整的菜鸟(第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);
}
}
在我看来,最好将汽车和自行车分成两个单独的类“ Car”和“ Bike”,然后创建第三个类来容纳这些对象的集合,这样您就可以使用列表或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接受车辆类型的对象,汽车和自行车都将车辆扩展,因此它们将被接受。
我注意到CarAndBikes
的toString()
方法在数组引用上使用toString()
(并且数组不会覆盖toString()
)。 你可以像这样使用Arrays.toString(Object[])
public String toString() {
// return "(" + items + ")";
return Arrays.toString(items);
}
您获取的Object.toString()
被记录为:
类
Object
的toString
方法返回一个字符串,该字符串包括该对象是其实例的类的名称,符号字符“ @”以及该对象的哈希码的无符号十六进制表示形式。 换句话说,此方法返回的字符串等于:getClass().getName() + '@' + Integer.toHexString(hashCode())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.