简体   繁体   中英

What is the use of Constructor in Java when you can call class variable using object.(variable_name)?

In the below example we can initialize class variable using the constructor ie, this keyword or by through an object. Can someone answer then why do we use constructor to pass the value or initialize a variable:

public class Car {
    
    String color;
    int price;

    public static void main(String[] args) {
        Car obj = new Car();
        obj.color = "Red";
        obj.price = 80;
        System.out.println(obj.color + " "+ obj.price);
        
        
        Car obj1 = new Car();
        obj1.color = "White";
        obj1.price = 70;
        System.out.println(obj1.color+" "+obj1.price);
    }
}

You can, but you shouldn't. The constructor helps keep the integrity of the object.

When you put your initialization sequence in the constructor, you assure that the object will be consistent. When you put your initialization outside, you delegate the control to other entities that may not be aware of your class requirements.

For instance, in your example, you can instantiate a Car without color or price, which may be a requirement for your model. In a more complex example, it may be difficult to keep all the object fields consistent, especially if you have calculated fields. That is why it is a bad practice that may lead to bugs.

Also, it is not recommended to access class fields externally. In java, it is best to use get and set methods because it provides more control.

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