下面是一个Java汽车程序,我可以存储模型,make等...我想添加一个名为VehicleDB的新类,它通过addVehicle方法将Vehicle或Car添加到数据库中。然后我想要一个方法,通过VehicleDB类中的print方法打印数据库中的所有车辆。我如何参考VehicleDB中Vehicle和Class中的两个原始现有打印方法?三江源。
class Vehicle {
int capacity;
String make;
int setCapacity;
Vehicle(int theCapacity, String theMake) {
capacity = theCapacity;
make = theMake;
}
int setCapacity(int setCapacity){
capacity = setCapacity;
System.out.println("New capacity = " + setCapacity);
return setCapacity;
}
void print() {
System.out.println("Vehicle Info:");
System.out.println(" capacity = " + capacity + "cc" );
System.out.println(" make = " + make );
}
}
class Car extends Vehicle {
String type;
String model;
void print(){
super.print();
System.out.println(" type = " + type);
System.out.println(" model = " + model );
}
Car(int theCapacity, String theMake, String theType, String theModel){
super(theCapacity, theMake);
this.type = theType;
this.model = theModel;
}
@Override
int setCapacity(int setCapacity){
System.out.println("Cannot change capacity of a car");
return capacity;
}
}
class VehicleDB {
void addVehicle(Vehicle Vehicle){
}
void print(){
System.out.println("=== Vehicle Data Base ===");
}
}
class Task4 {
public static void main(String[] args) {
VehicleDB db = new VehicleDB();
db.addVehicle(new Car(1200,"Holden","sedan","Barina"));
db.addVehicle(new Vehicle(1500,"Mazda"));
db.print();
}
}
答案 0 :(得分:1)
如果将数据存储在ArrayList中,
class VehicleDB {
ArrayList<Vehicle> db = new ArrayList<Vehicle>();
void addVehicle(Vehicle c){
db.add(c);
}
void print(){
System.out.println("=== Vehicle Data Base ===");
for(Vehicle v: db){
v.print();
}
}
}