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

Мне просто нужна помощь в остановке метода печати.он выводит мой вывод дважды как car1.print ();car2.print ();находится в методе печати в нижней части.Как я могу исключить это, не удаляя его.Его нужно поместить в часть super.print ().

class Vehicle {  // base class

   int capacity;
   String make;

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

Ответы [ 4 ]

0 голосов
/ 16 октября 2018

Одним из решений является вызов конструктора базового класса из дочернего класса с использованием ключевого слова super и добавление других параметров из конструктора дочернего класса, как упомянуто @ Mureinik

В зависимости от требований базового класса вы также можете попробоватьиспользуя абстрактные методы.Пример кода ниже.

abstract class Vehicle {

   static int capacity;
   static String make;

   Vehicle(int theCapacity, String theMake) {
      capacity = theCapacity;
      make = theMake;
   }

   protected static void print() {
      System.out.println("Vehicle Info:");
      System.out.println("  capacity = " + capacity + "cc" );
      System.out.println("  make = " + make );
      // you can use these methods where you want in this base class.
      System.out.println("  type = " + getType());
      System.out.println("  model = " + getModel());

   }
   protected abstract  String getType();
   protected abstract  String getModel();
}


public class Car extends Vehicle{

    Car(int theCapacity, String theMake) {
        super(theCapacity, theMake);
    }
/**
 * @param args
 */
    public static void main(){

        print();
    }

    @Override
    protected String getType() {
        // TODO Auto-generated method stub
        return "Audi";
    }
    @Override
    protected String getModel() {
        // TODO Auto-generated method stub
        return "Q7";
    }

    }
0 голосов
/ 16 октября 2018

Вам не хватает Constructor

public Car (int theCapacity, String theMake, String theType, String theModel) {
  capacity = theCapacity;
  make = theMake;
  Type = theType;
  Model = theModel;
}

или

public Car (int theCapacity, String theMake, String theType, String theModel) {
  super (theCapacity, theMake);
  Type = theType;
  Model = theModel;
}
0 голосов
/ 16 октября 2018

Вы должны вызвать супер-конструктор, просто передав параметры в дочерний класс.

public Car(int capacity, String make, String type, String model) {
      super(capacity, make); // simply call super
      this.type = type;
      this.model = model;
   } 
0 голосов
/ 16 октября 2018

Вы можете использовать ключевое слово super в конструкторе, чтобы вызвать конструктор суперкласса и передать ему параметры.Обратите внимание, что это должен быть первый оператор в конструкторе:

class Car extends Vehicle {
   public String type;
   public String model;


   public Car(int theCapacity, String theMake, String theType, String theModel) {
      super(theCapacity, theMake); // Here
      type = theType;
      model = theModel;
   }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...