-3

In the below example we can initialize class variable using the constructor i.e., 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);
    }
}
luk2302
  • 55,258
  • 23
  • 97
  • 137
  • 3
    Because that way we can force the programmer to pass a color and a price. Right now nothing is stopping you from creating a car that has no color and no price, which most likely does not make any sense. – luk2302 May 26 '21 at 12:16
  • 1
    and what about the fields being `private` and used from a different class (no access to these fields)? Or just to initialize the instance (would you know all fields that must be set when creating a new `Pattern`, even a `String`?) –  May 26 '21 at 12:17
  • 1
    @user15793316 to play devils advocate here: why do we make fields `private` at all, isn't it much easier to code if everything is `public`? ;) – luk2302 May 26 '21 at 12:18
  • Using your car constructor above (the implicite one) does not initialize your member variables. They stay null until you set it by setter or directly, as you did. If you add a constructor, a lik2302 wrote, you force the programmer to init them by constructor. The implicite defaut constuctor is deactivated then, if you don't add it manually again. – Maik May 26 '21 at 12:22
  • Does this answer your question? [Purpose of a constructor in Java?](https://stackoverflow.com/questions/19941825/purpose-of-a-constructor-in-java) – Cemal May 26 '21 at 13:55
  • This helps. Thank you! – Automation Tester May 26 '21 at 16:32

1 Answers1

0

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.

felipecrp
  • 999
  • 10
  • 16