0

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

4

2 回答 2

1
//You Car class should look like this

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

// This is the Car class constructor

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


// This is where you call the Car class. You create a new class MyCar to call my class

public class MyCar {
        public static void main(String[] args) {
            Car car = new Car("1990 Mustang", 4, 140, 40000);
            System.out.println(car);

// Output : 1990 Mustang, 4, 140, 40000



        }
}
于 2019-09-13T16:12:58.597 回答
1

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

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

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

例如,

int numberOfDoors = car.numberOfDoors;

我们通常将字段设为私有并通过 getter 访问它们:

int numberOfDoors = car.getNumberOfDoors();

假设有一个方法getNumberOfDoors定义为

public int getNumberOfDoors() {
    return this.numberOfDoors;
}
于 2019-09-12T23:50:39.570 回答