A Constructor is code that is invoked when an object is created from the class. You do not need to write a constructor for every class. If a class does not have a user-defined constructor, an implicit, no-argument, public one is used.
public class AClass {
// No argument Constructor
public AClass() {
//Constructor code
}
}
Object can be instantiated as below -
AClass obj = new AClass();
If you write a constructor with argument(i.e parametrised constructor), you can use that constructor to create an object using those argument. If a class contain parametrised constructor, then default constructor wont create by automatically,you need to create no-argument constructor explicitly.
# Constructor can be overloaded i.e. there can be more then one Constructor for a class, each having different parameters.
# One constructor can call another constructor using this(...) syntax also called as Constructor chaining as in below example with no argument and one argument constructor.
public class TestClass2 {
private static final Integer DEFAULT_SIZE = 10;
Integer size;
//Constructor with no arguments
public TestClass2() {
this(DEFAULT_SIZE); // Using this(...) calls the one argument constructor
}
// Constructor with one argument
public TestClass2(Integer ObjectSize) {
size = ObjectSize;
}
}
Object can be instantiated either -
TestClass2 objOne = new TestClass2();
TestClass2 objTo = new TestClass2(31);
# Constructor overloading- Constructor with different order argument is possible
public class Leads {
//No-argument constructor
public Leads () {}
// A constructor with one argument
public Leads (Boolean call) {}
// A constructor with two arguments
public Leads (String email, Boolean call) {}
// Though this constructor has the same arguments as the one above, they are in a different order, so this is legal
public Leads (Boolean call, String email) {}
}





