Guys can you help me to understand Constructors im kinda confuse of it i need a little help.... | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Guys can you help me to understand Constructors im kinda confuse of it i need a little help....

Tnx guys

8th Nov 2017, 3:00 AM
Rick Nocidad
Rick Nocidad - avatar
2 Answers
+ 12
As @Jay said, we can't create an object without calling constructor. Some key points: 1. Constructor name must be same as the class name 2. Although constructor can be considered as a special kind of method, there will be no return type (not even void). This is how we can distinguish between a constructor and a general method. Person() // this is a constructor void Person() // this is a method 3. Constructor may or may not have any parameter. If you do not write any constructor, a no-arg constructor will work by default. 4. You can write multiple constructors by overloading if required. Person() Person(String name) Person(String name, int age) Person(int age) .... Example: If Person is a class with member variables: name and age, then constructor should look like: Person(){ // without argument } or, Person(String n, int a) // with argument name = n; age = a; } or, similar overloaded constructors..... Now, while creating object, you must call any constructor using "new" keyword. Person p = new Person(); or, Person p = new Person("Rickyy", 15); // "Rickyy" and 15 will be passed to the constructor as name and age and assign the values
8th Nov 2017, 3:45 AM
Shamima Yasmin
Shamima Yasmin - avatar
+ 8
In c++ Constructors are used (called) when a class object is first instanced. They are useful for setting any variables or parameters the object may need to function correctly. Pretty sure the same goes for Java
8th Nov 2017, 3:15 AM
jay
jay - avatar