【问题标题】:stop output from printing twice停止打印两次输出
【发布时间】:2019-03-20 17:40:15
【问题描述】:

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

【问题讨论】:

  • 不删除代码,你不能:)
  • {} 没有做任何事情。里面的任何东西都只是构造函数的一部分。不太确定您在这里真正需要什么。
  • 你的类Vehicle中有一个方法print(),我猜……你为什么在Car的构造函数中调用它(super.print()和 之后显式打印它们的值(通过car1.print()car2.print())?只需摆脱其中一个调用...另一个想法是在每个类中提供适当的toString() 并打印出来。
  • 您能添加实际结果和预期结果吗?
  • 您能否将预期的输出也添加到问题中

标签: java printing superclass


【解决方案1】:

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

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

}

【讨论】:

    猜你喜欢
    • 2014-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-21
    • 2020-10-24
    • 2015-01-05
    • 2022-06-17
    • 1970-01-01
    相关资源
    最近更新 更多