[英]Calling methods from 2 classes
Below is a Java car program where I can store the model, make etc... I want to add a new class called VehicleDB which adds a Vehicle or Car to a database through the addVehicle method.下面是一个 Java 汽车程序,我可以在其中存储模型、制作等……我想添加一个名为 VehicleDB 的新类,它通过 addVehicle 方法将车辆或汽车添加到数据库中。 Then I want to have a method which prints all the Vehicles out in the database through the print method in the VehicleDB class.然后我想要一个方法,通过 VehicleDB 类中的打印方法将数据库中的所有车辆打印出来。 How would I refer to the two original existing print methods in Vehicle and Class in VehicleDB?我将如何引用 VehicleDB 中 Vehicle 和 Class 中的两个原始现有打印方法? Thankyou.谢谢你。
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();
}
}
If you store your data in a ArrayList,如果您将数据存储在 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.