остановить вывод из печати дважды - PullRequest
0 голосов
/ 16 октября 2018

У меня есть код ниже, который печатает вывод дважды.Как мне распечатать только две нижние строки без печати 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 голосов
/ 16 октября 2018

Вы можете реализовать метод 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();
    }

}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...