You have already learned the basics of Java including the fields and methods, the if statement, the loops and the switch statements. We will now go deeper in java by teaching how to create a Java Constructor. Each java class contains a constructor and is just like methods that are being called when initializing a class.
Constructors are defined with a modifier and the class name plus opening and closing parenthesis:
public class MainClass { public MainClass() { //this is a constructor } }
All class has at least one constructor. If a class file doesn’t define a constructor, a default one will be created for you. A constructor should ultimately call the superclass constructor using the method super() before executing its own logic. You will learn more about the superclass and the subclass in the preceding chapters.
Constructors are the first method that will be called when initializing a class. For example,
public class MainClass { public int firstNum; public int secondNum; public MainClass() { //this is the constructor firstNum = 5; secondNum = 10; } public void addNumbers(){ int answer = firstNum + secondNum; System.out.println(“The sum of two numbers is: “+answer); } public static void main(String args[]){ //Create new instance of MainClass MainClass myClass = new MainClass(); myClass.addNumbers(); } }
Above is our class MainClass. Inside our class, we have the constructor, the addNumbers method, and our main method. Remember that in the past tutorial, the first method that is being called is always the main method. Here’s what will happen if we run our program.
In java, you can actually create multiple constructors. The compiler will just find the matching constructor upon instantiation. Consider the example below:
public class MainClass { public int firstNum; public int secondNum; public MainClass() { //this is a constructor firstNum = 5; secondNum = 10; } public MainClass(int x, int y) { //this is also a constructor firstNum = x; secondNum = y; } public void addNumbers() { int answer = firstNum + secondNum; System.out.println(“The sum of two numbers is: “+answer); } public static void main(String... args) { //Create new instance of MainClass MainClass myClass = new MainClass(20, 30); myClass.addNumbers(); } }
In the above example, we have two constructors. One without parameters and the other one that requires two integers. Let’s checked what happened:
That’s it. Practice yourself to create a java class and create your own java constructor instead of relying on the default constructor. Next on our tutorial is how to implement inheritance by using the extends keyword.