在构造函数中将对象作为参数传递

时间:2018-06-25 01:11:26

标签: java

我试图将一个对象作为参数传递给构造函数。是否允许以下​​代码?特别是我将ToyotaCorolla传递到Car car,然后传递到String brandString model的部分。

public class Car {
    private String brand, model;

    public Car(String brand, String model) {
        this.brand = brand;
        this.model = model;
    }

    // getters and setters
}

public class Customer {
    private String name;
    private Car car;

    public Customer(String name, Car car) {
        this.name = name;
        this.car = car;
    }

    // getters and setters
}

public class Service {
    Customer customer = new Customer("John", "Toyota", "Corolla");
}

2 个答案:

答案 0 :(得分:7)

客户没有使用3个字符串的构造函数,因此必须在以下位置传递一个String和一个Car对象:

更改

Customer customer = new Customer("John", "Toyota", "Corolla");

Customer customer = new Customer("John", new Car("Toyota", "Corolla"));

解决方案2是为客户提供3字符串构造函数,并在构造函数中创建Car对象。

public Customer(String name, Car car) {
    this.name = name;
    this.car = car;
}

// and
public Customer(String name, String brand, String model) {
    this.name = name;
    this.car = new Car(brand, model);
}

答案 1 :(得分:1)

将您的Service类更改为:-

public class Service {
    Customer customer = new Customer("John", new Car("Toyota", "Corolla")); 
}