停止输出打印两次

stop output from printing twice

我在下面有一些代码可以打印输出两次。我如何只打印底部的两行而不打印 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();
   }
}

您可以使用 super.print() 在 class Car 中实现 print() 方法,就像您使用 super 的构造函数实现 Car 的构造函数一样class Vehicle.

看看这个基本示例实现(我不得不猜测 class 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);
    }
}

在classCar中,只需覆盖方法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 方法 class:

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

}