Constructor in java
Constructor is an interesting concept in java. A constructor is used to initialize the object.
In other words, a constructor is invoked when we create any object.A constructor initializes the data for the object.
Rules for constructor:
- Constructor name must be same as the class name
- Constructor must not have any explicit return type
There are 2 types of constructors in java.
- Default constructor
- Parameterized constructor
Default Constructor: A constructor that does not have any arguments is called default constructor.
When we create the object of SubNumber class in the below example, default constructor will be called.
package com.testingpool.demo2; public class SubNumber { SubNumber(){ System.out.println("This is a default constructor"); } public static void main(String[] args) { SubNumber sub = new SubNumber(); } }
Parameterized Constructor: A constructor which has parameters is known as Parameterized constructor. We can have any number of parameters in the constructor and we can initialize objects with the same no. of parameters as per parameterized constructor.
package com.testingpool.demo2; public class SubNumber { SubNumber(int a,int b){ // parameterized constructor int c = a+b; System.out.println("The sum is "+c); } public static void main(String[] args) { SubNumber sub = new SubNumber(4,5); //create object } }
What is constructor overloading?
That means we can have more than one constructor but with different number of parameters.
package com.testingpool.demo2; public class SubNumber { SubNumber(int a,int b){ // 1st parameterized constructor 1 int c = a+b; System.out.println("Output of 1st constructor "+c); } SubNumber(int x,int y,int z){ // 1st parameterized constructor 1 int d = x+y+z; System.out.println("Output of 2nd constructor "+d); } public static void main(String[] args) { SubNumber sub = new SubNumber(4,5); //create object for 1st constructor SubNumber sub1 = new SubNumber(2,4,6); //create object for 1st constructor } }
What is the role of a default constructor?
Default constructor assigns the default values to object or data members like 0 to int, null to String etc.
package com.testingpool.demo2; public class SubNumber { int a; String b; SubNumber(){ System.out.println(a +"----"+b); } public static void main(String[] args) { SubNumber sub = new SubNumber(); //create object for constructor } }
Does constructor return any value?
Yes, it returns class instance. We cant use return type.
What else constructor can do?
It can be used like a method i.e. we can create object, call methods etc inside it.