Easy Tutorial
For Competitive Exams

Java Programming Constructor

What is Constructor?

A constructor is a special method that is used to initialize an object.

Constructor name is same as class name.

Constructor does not have any return type.

How to call a constructor?

Constructor of a class is automatically invoked everytime an instance of a class is created.

Types of Constructor:

  • Default constructor
  • no-arg constructor
  • Parameterised Constructor

What is Default constructor?

Every class in Java, has a constructor. If you do not define any constructor in your class, java generates one for you by default. This constructor is known as default constructor. You would not find it in your source code but it would present there. It would look like this if you could see it. Default constructor for class Demo:

Example

public Demo(){
}

What is no-arg constructor?

Constructor with no arguments is known as no-arg constructor. The signature is same as default constructor, however body can have any code unlike default constructor where the body does nothing.

Example

public class Demo{
public Demo(){
System.out.println("This is a default constructor");
 }
public static void main(String args[]){
  Demo a1=new Demo();
   }
}
Try it Yourself

What is Parameterized constructor?

Constructor with arguments is known as parameterized constructor.

Example

class Demo{
public Demo(int num, String str){
System.out.println(num+" "+str);
}
public static void main(String args[]){
Demo a1=new Demo(121,"aaa");
  }
}
Try it Yourself

What is Constructor Overloading?

Like method overloading, Java also supports constructor overloading. Writing multiple constructors, with different parameters, in the same class is known as constructor overloading.

Depending upon the parameter list, the appropriate constructor is called when an object is created.

Example

public class Student{
  public Student(){
    System.out.println("Hello 1");
  }
  public Student(String name){          
    System.out.println("Student name is " + name);
  }
 
  public Student(String name, int marks){
    System.out.println("Student name is " + name + " and marks are " + marks);
  }
 
  public static void main(String args[]){
    Student std1 = new Student();                
    Student std2 = new Student("John");       
    Student std3 = new Student("Dora", 56);    
  }
}
Try it Yourself

Solve this!!

11590.What is the prototype of the default constructor of the class?
public class Test { }
public Test(void)
int Test( )
Test(void)
public Test( )
11591.Which of the modifier can't be used for constructors?
public
private
static
protected
11592.What is the output of the above program ?
class Num  {
      Num(double x ){
              System.out.println( x ) ;
      }   
}
public class  Test {
       public static void main(String[] args){
                  Num num = new Num( 2 ) ;
       }     
}
0
Error
2.0
2
Share with Friends