我是一个相对较新的 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/