ConstructorsConstructors in Java are used to create an instance of a class. And in Java, that is huge because everything in Java are practically classes. And those that are not classes are primitives. A class in Java can also be represented as an Object. So you can conclude that Java is comprised of classes and primitives. If constructors don't exist and you have no other ways to get an instance of a class, then coding is still possible with Java; however, your code will not be as secure as you would like it to be. Let's take a look at an example:
public class Test {
private a;
private b;
private c;
public Test (int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
}
The class's name is Test as you can see in the first line. The constructor is:
public Test (int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
Constructors don't really do anything except initialize class fields. You can have it do other stuff, of course. You can have the constructor run methods within the class or from other classes. In the constructor I used, I just set the class's variables (a, b, c) to the ones given. If you are confused, then here's an example to clarify that (or I hope it does):
Test t = new Test(4, 6, 7);
That's a line of code that creates a new instance of the class Test with values 4, 6 and 7. You may ask, so what? Well, let's say we had a method in the class that adds up the numbers.
public class Test {
private a;
private b;
private c;
public Test (int a, int b, int c) {
this.a = a;
this.b = b;
this.c = c;
}
public int sum () {
return this.a + this.b + this.c;
}
}
With that new update on the class Test, we can use the method sum().
int sum = t.sum();
Since the instance of the class called t already contains the values for the numbers when we initialized it, we do not have to pass any arguments to the sum() method. With constructors, you can create as many instances of the class as you want. Let's do that.
Test a = new Test(1,2,3);
Test b = new Test(4,5,6);
Test c = new Test(7,8,9);
If I call the method sum() on all of them, then Test a will be 6, Test b will be 15, and Test c will be 24. That's it for the sum() method. You can also add in an average method inside the class Test and every instance of Test will have that method. So as you can see, creating instances of a class is big in Java. And that's why we need constructors.
Other than the basics, there is not much more to say about constructors. They are basic concepts.
Happy programming,
Eureka