Here In this post we will discuss about Constructors in Java. In the preceding posts we have discussed about class and instance variables.
What is Constructor in Java?
Constructor is a special method to initialize objects having same name as class name. I’ll describe some points about Constructors and try to illustrate these points with the help of code. Look at following points.
- Constructors must have same name as Class Name.
- Constructors never have return type.
- Constructor is called automatically at the time of object creation.
- If You do not define a constructor, Then compiler automatically generate a constructor with empty implementation.
Types Of Constructors in Java
- Default constructor
- Parameterized constructor
Default Constructor:
The constructor having no argument is Default Constructor in Java. Automatically generated constructor is also a type of default constructor.
Lets have a code below:
Example 1:
package package1; public class DefaultDemo{ int x; public static void main(String ag[]){ DefaultDemo dc=new DefaultDemo(); } }
Now type javap command with class name as shown in following screenshot.
Take a bit special care in this example. Compile the program before using javap tool. In above output we can see a Default constructor generated by compiler during compilation. And object is created by virtue of default constructor.
Parameterized Constructor:
Constructor with parameters is called parameterized constructors. We need to pass these parameters with new operator at the time of object creation. Generally parameters passed to constructor are used to initialize instance variables in the class.
There may be more than one constructors in a java class. It means we can apply concept of overloading in Constructors in Java.
Lets have an example code again:
Example 2:
package package2; public class FirstClass { int var1; FirstClass(){ System.out.println("Object creation"); } FirstClass(int x){ var1=x; System.out.println("Object creation with params "+var1); } public static void main(String[] args) { FirstClass fc=new FirstClass(); FirstClass fc2=new FirstClass(12); } }
Output of this code will appear like this.
Output
Object creation
Object creation with params 12
Some more Points about Constructors in Java
- Constructor do not have return type but it returns an instance of that class.
- If you use return type either void or any other, then that method will not treated as constructor. It will be treated as general method.
- You can apply any Java access modifier with constructor.
- If you are going to extend some class and want to use constructor in derived class, then you must define a default constructor on super class.
- Constructor is not regarded as member of class, Hence can not be called with object or class name.
Ok guys, I hope this article is helpful for you for having better understanding of Constructors in Java.