Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/365.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 停止打印输出两次_Java_Printing_Superclass - Fatal编程技术网

Java 停止打印输出两次

Java 停止打印输出两次,java,printing,superclass,Java,Printing,Superclass,我在下面有一些代码,可以将输出打印两次。如何只打印底部的两行而不打印car1.print()car2.print()也是。我认为它必须是super.print()的一部分 您可以使用super.print()在类Car中实现print()方法,就像您使用超级类Vehicle的构造函数实现Car的构造函数一样 看看这个基本的示例实现(我不得不猜测类车辆的设计): 在类Car中,只需重写方法print()并首先调用super.print(),然后打印Vehicle没有的成员: public clas

我在下面有一些代码,可以将输出打印两次。如何只打印底部的两行而不打印
car1.print()
car2.print()也是。我认为它必须是
super.print()的一部分


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

看看这个基本的示例实现(我不得不猜测类
车辆的设计):

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

}

如果不删除代码,您就不能:)
{}
没有做任何事情。里面的东西只是构造器的一部分。我不太确定您在这里真正需要什么。我想您的类
车辆
中有一个方法
print()
。。。为什么在
Car
的构造函数中调用它(by
super.print()
),然后显式地打印它们的值(by
car1.print()
car2.print()
)?把这些电话中的一个处理掉。。。另一个想法是在每个类中提供一个适当的
toString()
,并打印出来。您能添加实际和预期的结果吗?您能将预期的输出也添加到问题中吗
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);
    }
}
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();
    }

}