Constructors are special type of methods that are invoked at the time of creating the objects. If you use new keyword for creating the object, the constructors are called. There are certain restrictions imposed on these special type of methods.
- Constructors should have the same name as class name
- Constructors should not have any return type
- There are two types of constructors.
- Default constructor
- Parameter used constructor
- There can be more than one constructors for a class. It implies that constructors can be overloaded.
- Constructor can be declared as private, default, protected and public access.
- If you declare private constructor, then you can not create instance for that class by invoking the constructor from other classes.
- If there is no constructor specified in a class, compiler creates default no-argument empty constructor.
Constructor Example
Look at the constructor syntax to understand it better.
package javabeat.net.core; public class ConstructorDemo { private int i; //Default Constructor ConstructorDemo(){ this.i = 10; System.out.println("Default Constructor Called!"); } //Parameter Constructor public ConstructorDemo(int i){ this.i = i; System.out.println("Parameter Constructor Called!"); } public static void main (String args[]){ ConstructorDemo demo1 = new ConstructorDemo(); ConstructorDemo demo2 = new ConstructorDemo(20); System.out.println(demo1.i); System.out.println(demo2.i); } }
Output of the above example will be:
Default Constructor Called! Parameter Constructor Called! 10 20