Constructors
Whenever an instance is created in the method, it is called the constructor of that particular class and is executed by default.
If the user has not written/provided any constructor, the compiler will automatically insert the empty constructor.
A method name similar to its respective class name and method does not return any value.
Overloading is possible but not overriding.
An example of a Java program with a constructor chain
The following is an example of a constructor chain in a Java program:
package MyFirstPackage; class SampleClass4 { SampleClass4(){ System.out.println("executing sample meathod"); } } class SampleClass3 extends SampleClass4 { SampleClass3(){ System.out.println("executing sample method 2"); } } public class Constructors { public static void main(String[] args) { new SampleClass3(); } }
The output for the preceding code is as follows:
executing sample meathod executing sample method 2