简体   繁体   中英

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. Then I want to have a method which prints all the Vehicles out in the database through the print method in the VehicleDB class. How would I refer to the two original existing print methods in Vehicle and Class in VehicleDB? 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,

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();
      }
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM