[英]Calling methods from 2 classes
下面是一個 Java 汽車程序,我可以在其中存儲模型、制作等……我想添加一個名為 VehicleDB 的新類,它通過 addVehicle 方法將車輛或汽車添加到數據庫中。 然后我想要一個方法,通過 VehicleDB 類中的打印方法將數據庫中的所有車輛打印出來。 我將如何引用 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();
}
}
如果您將數據存儲在 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();
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.