Search This Blog

Monday 3 April 2017

Constructors in Java

Constructors in Java

A constructor in Java is a block of code similar to a method that’s called when an instance of an object is created. A constructor is a special method that is used to initialize an object. Every class has a constructor, if we don't explicitly declare a constructor for any java class the compiler builds a default constructor for that class. A constructor does not have any return type.
A constructor has same name as the class in which it resides. Constructor in Java cannot be abstract, static, final or synchronized. These modifiers are not allowed for constructor.
public class Student {
int rollNumber;
String name;

public Student() {
            rollNumber=0;
            name="";
            System.out.println("Inside Default Constructor");
}
}

There are two types of Constructor

·         Default Constructor – is the one which does not have any parameters
·         Parameterized constructor – may contain 1 or more parameter list.

If we don't explicitly declare a constructor for any java class the compiler builds a default constructor for that class

public class Student {
int rollNumber;
String name;

// Default Constructor
public Student() {
            rollNumber=0;
            name="";
            System.out.println("Inside Default Constructor");
}
// parameterized constructor
Student(int rno,String sname){
            rollNumber=rno;
            name=sname;
System.out.println("Inside Parametrized Constructor");
}
}

Constructor Overloading

Like methods, constructors can also be overloaded. Overloaded constructors are different on the basis of their type of parameters or number of parameters. Constructor overloading is not much different than method overloading. In case of method overloading you have multiple methods with same name but different signature, whereas in Constructor overloading you have multiple constructor with different signature.

Let’s create a class with the main method to class the Student Class
public class MainClass {
public static void main(String[] args) {
            // Default Constructor will be called
            Student s1=new Student();
           
            // Calling Parametrized Constructor
            Student s2=new Student(1,"Bond");
}
}

Once we execute the above class, we get the following output
Inside Default Constructor
Inside Parametrized Constructor

Some of the key points to remember regarding Constructors
·         A constructor doesn’t have a return type.
·         The name of the constructor must be the same as the name of the class.
·         Unlike methods, constructors are not considered members of a class.
·         A constructor is called automatically when a new instance of an object is created.
·         Constructors can be overloaded just like normal methods.
·         Constructors can be private. This facilitates Singleton Design Pattern.


3 comments: