Constructors are a special type of function which the name is the same as class name. And it is automatically invoked (called) when object of class is creative. Constructor has following features.
- Constructor name must have class name
- Constructor have no any return type even “void”.
- We cannot call constructor explicitly
- Constructor can be overloaded
- Constructor cannot be inherited
- We cannot make constructor private
There are four type of constructors in JAVA.
- Default constructor (make java)
- Non parameterize / normal constructor.
- Parameterize constructor
- Copy constructor
Default Constructor
This constructor is automatically provided by java. This facility is provided only when programmer does not make any type of constructor
Example:
The above program contains a single class A which has no method or constructor so according to the rule java automatically provides the default constructor in class A. We can check the default constructor by using command,
E:\Java>javac [programfile name]
E:\java>javap [class name]
Non – Parameterized Constructor
We can make our own constructor without any parameter. The main purpose of constructors are to provide default value in variable and perform some startup code.
- class A
- {
- inti=100;
- A()
- {
- i=200;
- }
- void show()
- {
- System.out.print(i)
- }
- }
-
- class B
- {
- public static void main(String ...args)
- {
- A ob =new A();
- ob.show();
- }
- }
Parameterized Constructor
In parameterize constructor we pass the value to the constructor at time of object creation.
Example
- class A
- {
-
- A(inti)
- {
- System.out.print(i)
- }
- void show()
- {
- System.out.print("Hello Parametrized Constructor")
- }
- }
-
- class B
- {
- public static void main(String ...args)
- {
- inti=20;
- A ob =new A(i);
- ob.show();
- }
- }
Note
When we create our own parameterized constructor then we cannot create any object with the help of default constructor. If you want to create a new object with the help of default constructor then we must explicitly type a new constructor in the class.
Copy Constructor:
With the help of copy constructor value of one object is assigned to another object at the time of object creation.
Example:
- class A
- {
- int n1,n2;
- A (inti,int j)
- {
- n1=i;
- n2=j;
- }
- A (A ref)
- {
- n1=ref.n1;
- n2=ref.n2;
- }
- void show()
- {
- System.out.print(n1);
- System.out.print(n2);
-
- }
- }
-
- class B
- {
- public static void main(String ...args)
- {
- A ob1=new A(10,20);
- ob1.show();
- A ob2=new A(ob1);
- ob2.show();
- }
- }
Important fact about constructor –if we write the return type in any constructor then it will not flag any error but now it behaves like normal function.