java - 我已经编写了构造函数类,但我需要测试它。我怎么做?

标签 java class-constructors

我是一个相对较新的 Java 程序员,我正在学习构造函数。我已经掌握了如何构建构造函数本身的格式,但我的计算机科学老师要求我编写更多代码行以确保我的构造函数正常工作。

我浏览过其他网站,但它并没有真正给我我需要的东西。

我尝试过使用我认为在逻辑上可能有效的方法(输入“a.variable()”作为对象,但这也不起作用。

class Car {
    public String make;
    public String model;
    public int numberOfDoors;
    public int topSpeed;
    public int price;

    Car(String make, String model, int numberOfDoors, int topSpeed, int price){
        this.make = make;
        this.model = model;
        this.numberOfDoors = numberOfDoors;
        this.topSpeed = topSpeed;
        this.price = price;
    }

    Car(String make, String model, int topSpeed, int price){
        this.make = make;
        this.model = model;
        this.numberOfDoors = 4;
        this.topSpeed = topSpeed;
        this.price = price;
    }

    Car(int numberOfDoors, int topSpeed, int price){
        this.make = "unknown";
        this.model = "unknown";
        this.numberOfDoors = numberOfDoors;
        this.topSpeed = topSpeed;
        this.price = price;
    }

    Car(String make, String model, int numberOfDoors){
        this.make = make;
        this.model = model;
        this.numberOfDoors = numberOfDoors;
        this.topSpeed = 90;
        this.price = 0;
    }
}

我正在寻找可以打印出类似以下内容的东西:

1990 款野马,4 门,140 英里/小时,40000 美元

最佳答案

您需要做的就是使用适当的构造函数创建 Car 类的实例。

public class Example {
    public static void main(String[] args) {
        Car car = new Car("Mustang", "1990", 4, 140, 40000);
    }
}

创建实例 car 后,您可以访问其字段。

例如,

int numberOfDoors = car.numberOfDoors;

我们通常将字段设为私有(private)并通过 getters 访问它们:

int numberOfDoors = car.getNumberOfDoors();

假设有一个方法 getNumberOfDoors 定义为

public int getNumberOfDoors() {
    return this.numberOfDoors;
}

关于java - 我已经编写了构造函数类,但我需要测试它。我怎么做?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57915729/

相关文章:

java - 如何通过jsp页面中的超链接打开本地保存在Windows服务器上的pdf?

kotlin - Kotlin 中的构造函数与参数

java - 如何使用CountDownlatch使线程按顺序工作?

java - 如何将 ViewPager OnTouchListener 与 ImageView 一起使用,其中也有 OnClickListener

java - 如何使用 Java 从 Eclipse 中调用公共(public)方法的位置查看?

c++ - Qt继承和类构造函数混淆

c++ - 将基类 2 参数构造函数调用到子类 1 参数构造函数中

java - 使用Kotlin编译Java代码时报错: generics are not supported in -source 1. 3

java - 如何在 Java 中为构造函数编写 API 文档

c++ - 我可以在列表后面的初始化列表中使用初始化的 C++ 类成员吗?