Java Constructors

Java constructor is similar to the method. It calls when an object(instance) of a class is created. Allocated in the memory when a constructor is called. It is used to initialize the object of a class. When an object is created using the new keyword, constructor is called. It calls a default constructor if there is no constructor available in the class.

Types of Java Constructors:-

1-Default constructor:-
A constructor is called “Default Constructor” when a class does not have any parameter.
Example:-

class Demo
{ 
    Demo()
    {
       System.out.println("Object created");
    }  
    public static void main(String args[])
    {  
       Demo obj=new Demo();  
    }  
}

2- Parameterized constructor:-
A constructor which has a one or more number of parameters in the constructor is called a parameterized constructor.
Example:-

class Demo
{ 
    Demo(int x)
    {
       System.out.println("Value of x="+x);
    }  
    public static void main(String args[])
    {  
       Demo obj=new Demo(10);  
    }  
}
java java tutorials