代码之家  ›  专栏  ›  技术社区  ›  lefrost

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

  •  -1
  • lefrost  · 技术社区  · 6 年前

    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");
    }
    
    2 回复  |  直到 6 年前
        1
  •  7
  •   Hovercraft Full Of Eels    6 年前

    客户没有使用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);
    }
    
        2
  •  1
  •   Kartik    6 年前

    Service

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