0
In Java, what is the actual use of Constructors?
2 Réponses
+ 1
it is used to initialize fields for the object. for example if you have a Person class with 2 private int age and weight, when you create an object of this class you want these fields to get some values
+ 1
its not only about initialize fields,what about a default constructor?you use constructors to initialize an instance of an object.the constructor can take parameters to initialize values but does not have to.the “new“ call ,calls the constructor and creates an instance of an class as object which can be given values,but you can set values via the dot Operator (example.intVar = 2) or via a setter method as well.so its basically just the first method which is getting called when you create an object .(beside the static block and the instance initializer ( which is a method with only curly braces,and nothin else,this code goes straight to every constructor inside the Class).you can also create more then one constructor with different parameters just like overloaded methods.