0

Can someone tell me what constructors are?

28th Jul 2016, 8:48 AM
Ivan
Ivan - avatar
9 Answers
+ 2
Constructors are special type of methods that are instantiated upon their object creation.constructors have same name as class.. because whenever an object is created constructor should also invoke. For example when you open a application frame ,soon as the text fields,buttons everything will be invoked so no need of methods again..
28th Jul 2016, 9:03 AM
Manikanth Vanka
Manikanth Vanka - avatar
+ 2
Constructor in java is a special type of method that is used to initialize the object. Java constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the object that is why it is known as constructor.
13th Aug 2016, 12:28 PM
WPimpong
WPimpong - avatar
+ 1
Bit more elaborate of an explanation. Constructor is the constructor of a class. Say you have a class that gives definition of a person. Their age, name, height, etc.. If you defined the variables in the person class, you'd have to create a class for each person. Instead, you create the base class person, and give each variable to the constructor with no definition. This way, you can create multiple objects of the person class, passing different values during instantiation, the values defining the undefined variables in the person classes constructor, creating different people each time.
28th Jul 2016, 9:57 AM
James
James - avatar
+ 1
Ex. class Hello{ Hello(){ // Constructor } }
28th Jul 2016, 9:57 AM
Shubham Lenekar
+ 1
How do you use constructors?????
28th Jul 2016, 10:00 AM
Ivan
Ivan - avatar
+ 1
example. class Person{ String name; int age, height; public Person(String pName, int pAge, int pHeight){ name = pName; age = pAge; height = pHeight; } } This will create a constructor that take values of String, int and int. In another class, when you instantiate this class, you'd create it passing variables into the constructors arguments. Person person1 = new Person("bill", 33, 170); This will create an object of person with the 3 pieces of information passed to its constructor. What makes this useful is creating another object using different values. Person person2 = new Person("Mike", 22, 201);
28th Jul 2016, 10:07 AM
James
James - avatar
+ 1
Thanks James
28th Jul 2016, 10:37 AM
Ivan
Ivan - avatar
+ 1
the constructor is used to set the initial value of variable in its class. it has the same name of its class. when you create an object , the constructor set the initial values of attributes. in java the consructors are created automatically whether you defined it or not.
28th Jul 2016, 6:21 PM
Nermeen Ahmed
Nermeen Ahmed - avatar
+ 1
constructors are defined same name as class name
30th Jul 2016, 1:52 AM
Ravi Teja
Ravi Teja - avatar