+ 17

What is a constructor? How is it used?

5th Feb 2017, 7:24 PM
‎‏‎‏‎Joe
‎‏‎‏‎Joe - avatar
8 Answers
+ 13
thank you
10th Mar 2017, 8:24 PM
‎‏‎‏‎Joe
‎‏‎‏‎Joe - avatar
+ 7
When you want to use an object, you need to construct it. In other words, you use the constructor of an object to initialize it.
5th Feb 2017, 9:24 PM
Mohammad Mehrabi
Mohammad Mehrabi - avatar
+ 4
hi, a constructor is used to initialize the attributes of a class when you create an object. Let's you have a class like this: class person { String name; String surname; int age; //constructor public class(String name, String Surname, int age) { this.name = name; this.surname = surname; this.age = age; } } now when we create an object: person friend = new person("Jon", "Doe",18); //<<<constructor the values we passed in the brackets will be assigned to name, surname And age. so if we do: System.out.println(friend.name); it will print "Jon".
5th Feb 2017, 9:01 PM
Edi Lipovac
Edi Lipovac - avatar
+ 4
@Edi Which one is the main class? class person { String name; String surname; int age; or.... the second one
10th May 2017, 12:29 AM
ASDFG
ASDFG - avatar
+ 3
constructor is the first block of code will work when you create a new object from the class that the constructor represent it, in Java by default for any class you create there's a constructor without parameters, so if you create any parameterized constructor it's preferred to create an empty parameters constructor.
10th Mar 2017, 8:34 PM
AHMED SAMY
AHMED SAMY - avatar
+ 2
you can think of a constructor as an initializer. whenever an object is created with certain values . the constructor helps in initializing it with the associated values.
11th Feb 2017, 6:45 PM
Madhurima Chakraborty
Madhurima Chakraborty - avatar
+ 1
you declared a wrong constructor name. you declared "public class" instead of "public person"
16th May 2017, 10:58 AM
Sravan Kumar
Sravan Kumar - avatar
0
You is the first block of code which will be operated as soon as an object is created of any class.
17th Dec 2017, 9:54 AM
Rajat Gupta
Rajat Gupta - avatar