0

In Java, what is the actual use of Constructors?

4th Jun 2017, 1:03 AM
Jeet
Jeet - avatar
2 ответов
+ 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
4th Jun 2017, 1:09 AM
Giannis Tsirovasilis
Giannis Tsirovasilis - avatar
+ 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.
4th Jun 2017, 2:09 AM
JavaFreakz
JavaFreakz - avatar