繁体   English   中英

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

[英]Passing an object as a parameter in a constructor

我试图将一个对象作为参数传递给构造函数。 是否允许以下​​代码? 特别是我将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");
}

客户没有采用3个字符串的构造函数,因此您必须在以下位置传递字符串和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);
}

将您的Service类别更改为:-

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM