[英]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.在下面的示例中,我们可以使用构造函数即 this 关键字或通过 object 初始化 class 变量。 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.
构造函数有助于保持 object 的完整性。
When you put your initialization sequence in the constructor, you assure that the object will be consistent.当您将初始化序列放入构造函数时,您确保 object 将是一致的。 When you put your initialization outside, you delegate the control to other entities that may not be aware of your class requirements.
当您将初始化放在外面时,您将控制权委托给可能不知道您的 class 要求的其他实体。
For instance, in your example, you can instantiate a Car without color or price, which may be a requirement for your model.例如,在您的示例中,您可以实例化没有颜色或价格的汽车,这可能是您的 model 的要求。 In a more complex example, it may be difficult to keep all the object fields consistent, especially if you have calculated fields.
在更复杂的示例中,可能难以保持所有 object 字段一致,尤其是在您有计算字段的情况下。 That is why it is a bad practice that may lead to bugs.
这就是为什么这是一种可能导致错误的不良做法。
Also, it is not recommended to access class fields externally.此外,不建议从外部访问 class 字段。 In java, it is best to use get and set methods because it provides more control.
在 java 中,最好使用 get 和 set 方法,因为它提供了更多控制。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.