Search code examples
javaprintingsuperclass

stop output from printing twice


i have some code below that prints the output twice. how do i only print the bottom two lines without printing car1.print(); car2.print(); as well. i believe it has to be part of the 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();
   }
}

Solution

  • You can implement the print() method in the class Car using super.print() like you implemented the constructor of Car using the constructor of the super class Vehicle.

    Have a look at this basic example implementation (for which I had to guess the design of the 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);
        }
    }
    

    In the class Car, just override the method print() and call super.print() at first followed by printing the members that Vehicle does not have:

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

    You can try that in some main method in a solution 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();
        }
    
    }