我试图将一个对象作为参数传递给构造函数。是否允许以下代码?特别是我将Toyota
和Corolla
传递到Car car
,然后传递到String brand
和String 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");
}
答案 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"));
}