gpt4 book ai didi

java - 从父构造函数调用参数

转载 作者:行者123 更新时间:2023-11-30 05:57:46 24 4
gpt4 key购买 nike

如何调用父构造函数并给父构造函数参数为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();
}
}

最佳答案

public class VehicleDB {
private int n;

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

public class HoldenDB extends VehicleDB {

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

关于java - 从父构造函数调用参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52867278/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com