我下面有一些代码将输出两次打印。我如何只打印底部的两行而不打印car1.print();
car2.print();
。我认为它必须是super.print();
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;
super.print();
{
System.out.println(" type = " + theType);
System.out.println(" Model = " + theModel);
}
}
}
class Task1 {
public static void main(String[] args) {
Car car1 = new Car(1200,"Holden","sedan","Barina");
Car car2 = new Car(1500,"Mazda","sedan","323");
car1.print();
car2.print();
}
}
答案 0 :(得分:0)
您可以使用print()
在类Car
中实现super.print()
方法,就像您使用超类Car
的构造函数实现Vehicle
的构造函数一样
看看这个基本的示例实现(我不得不猜测类Vehicle
的设计):
public class Vehicle {
protected int capacity;
protected String make;
public Vehicle(int capacity, String make) {
this.capacity = capacity;
this.make = make;
}
public void print() {
System.out.println("Capacity: " + capacity);
System.out.println("Make: " + make);
}
}
在类Car
中,只需重写方法print()
并首先调用super.print()
,然后打印Vehicle
没有的成员:
public class Car extends Vehicle {
private String type;
private String model;
public Car(int capacity, String make, String type, String model) {
super(capacity, make);
this.type = type;
this.model = model;
}
@Override
public void print() {
super.print();
System.out.println("Type: " + type);
System.out.println("Model: " + model);
}
}
您可以在解决方案类的某些main
方法中进行尝试:
public class TaskSolution {
public static void main(String[] args) {
Vehicle car = new Car(1200, "Holden", "sedan", "Barina");
Vehicle anotherCar = new Car(1500, "Mazda", "sedan", "323");
System.out.println("#### A car ####");
car.print();
System.out.println("#### Another car ####");
anotherCar.print();
}
}