[英]Passing an object as a parameter in a constructor
我试图将一个对象作为参数传递给构造函数。 是否允许以下代码? 特别是我将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");
}
客户没有采用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.