0
Can someone tell me what constructors are?
9 Réponses
+ 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..
+ 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.
+ 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.
+ 1
Ex.
class Hello{
Hello(){ // Constructor
}
}
+ 1
How do you use constructors?????
+ 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);
+ 1
Thanks James
+ 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.
+ 1
constructors are defined same name as class name