简体   繁体   中英

Is it safe to assign default values to class members in Java?

Here's are two classes, Passenger and Car. Instead of initializing all private members of the Car class in all constructors, I thought of setting default values for them and overwriting specific members' values if provided by the instance creator.

import java.util.ArrayList;

class Passenger {
    private String name;

    Passenger(String name) {
        this.name = name;
    }
}

class Car {
    private String color = "red";
    private int numberOfWheels = 4;
    private ArrayList<Passenger> passengers = new ArrayList<Passenger>();

    Car() {}

    Car(String color) {
        this.color = color;
    }

    Car(int numberOfWheels) {
        this.numberOfWheels = numberOfWheels;
    }

    public void addPassenger(Passenger p) {
        this.passengers.add(p);
    }
}

Is it safe to set default values to class members like this? Any pitfalls to avoid for any particular data types (even other than the ones I have used)?

Yes, it is safe. Personally I prefer initialize where is declaration if is a common value for all constructors. If I have more constructor is not very pleasure to write that thing multiple times. And for me is more clear what value have.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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