Can anyone give me a simple constructor example please? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Can anyone give me a simple constructor example please?

i cant find anything that i can understand.

18th Jul 2017, 4:41 PM
D_Stark
D_Stark - avatar
8 Answers
+ 2
class Example{ Example(){ System.out.println("In Constructor."); } } class Program{ public static void main(String[] a){ Example obj1 = new Example(); } } Output: In Constructor.
18th Jul 2017, 5:08 PM
Rrestoring faith
Rrestoring faith - avatar
+ 3
Just to clarify, a constructor is what is always called when a new instance of the object is instantiated. You can define multiple constructors depending on whether you pass parameters into the constructor or not.
18th Jul 2017, 5:23 PM
S C
+ 2
@David Not quite. A constructor is exactly what @Sam said. The constructor is called upon instantiating an instamce of the class. This can optionally be done in the main method, but really can be anywhere. The key is that it is called when a class instance is created. A class instance can be created with the 'new' keyword.
18th Jul 2017, 9:27 PM
Rrestoring faith
Rrestoring faith - avatar
+ 1
Since it is called when an object (or class instance) is created, it can be used to do anything you want all classes to do when being created. Most commonly, to initialize variables. Example/ Person a = new Person("Fred", 21); Person b = new Person("Joe", 17); Person c = new Person("Amy", 17); class Person{ private String name; private int age; Person(String newName, int newAge){ // constructor name = newName; age = newAge; } } I just created 3 Person objects. Each object has it's own name and age, which was passed to the constructor which assigned the instance variables for the class. Now each person has an age and name! Each completely different from eachother.
18th Jul 2017, 9:37 PM
Rrestoring faith
Rrestoring faith - avatar
+ 1
"new Person(args);" Is saying: Create an instance of the Person class. Or, Create an Object of type Person. args is basically the arguments for the constructor you are calling. new Person(); Or new Person("Smith", 24);
18th Jul 2017, 10:40 PM
Rrestoring faith
Rrestoring faith - avatar
0
so a constructor is a statement in class with a parameter that you call from main?
18th Jul 2017, 8:57 PM
D_Stark
D_Stark - avatar
0
so what would you use a constructor for? as i dont see much diffrent from using void speak(){System.out.println("hello"); apart from you use the class name instead.. thanks
18th Jul 2017, 9:33 PM
D_Stark
D_Stark - avatar
0
Thanks faith, can i just pick your brain ^_^ can you tell me which part of this is the instance please i dont really know what it means but im assuming its in this statement somwere lol? person a = new Person ("Fred",21);
18th Jul 2017, 10:13 PM
D_Stark
D_Stark - avatar