从父构造函数调用参数

时间:2018-10-18 04:59:16

标签: java parameters constructor

如何调用父级构造函数并将父级构造函数的参数设置为50?我需要为HoldenDB创建一个没有正式参数的构造函数,并调用其父构造函数。
我首先将HoldeDB扩展到VechicleDB,但是,我不确定该如何进行。
如果有人可以帮助我,将不胜感激。

import java.util.ArrayList;

class Vehicle {

   int capacity;
   String make;
   
   void setCapacity(int setCapacity) {
      this.capacity = setCapacity;
      System.out.println("New Capacity = " + setCapacity);
   }

   Vehicle(int theCapacity, String theMake) {
      capacity = theCapacity;
      make = theMake;
   }

   void print() {
      System.out.println("Vehicle Info:");
      System.out.println("  capacity = " + capacity + "cc" );
      System.out.println("  make = " + make );
   }
}

class Car extends Vehicle {
   public String type;
   public String model;

   public Car(int theCapacity, String theMake, String theType, String theModel) {
      super(theCapacity, theMake);
      type = theType;
      model = theModel;
   }

   @Override
   public void print() {
      super.print();
      System.out.println("  type = " + type);
      System.out.println("  model = " + model);
      
   }
 
   @Override
   public void setCapacity(int setCapacity) {
      System.out.println("Cannot change capacity of a car");
   }
}
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();
      }
   }
}

class HoldenDB extends VehicleDB {
 
 void addCar(Vehicle c){
      db.add(c);
   }
   
}   
                       
class Task5 {
   public static void main (String[]args){
      HoldenDB db = new HoldenDB ();
      db.addCar(1200,"sedan","Barina");
      db.addCar(3800,"wagon","Commodore");
      db.print();
   }
}

1 个答案:

答案 0 :(得分:1)

public class VehicleDB {
    private int n;

    public VehicleDB(int n) {
        this.n = n;
    }
}

public class HoldenDB extends VehicleDB {

    public HoldenDB() {
        super(50);
    }
}