停止打印两次输出

时间:2018-10-16 08:35:12

标签: java printing superclass

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

1 个答案:

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

}