Java: Constructors


In Java, Constructors are used to creating and initializing the object’s state. The constructor also contains collections of statements to execute at time object creation.

Type of Constructors:

  • Default Constructor: A Constructor without any argument.
  • Parameterize Constructor: A Constructor with a number of arguments.

Points to Remember for Constructor

  • Constructor always has the same name as the class name in which it exists.
  • Constructor can not be used with keywords final, abstract, synchronized and static.
  • Constructors declaration with access modifiers can be used to control its access i.e so that restricts other classes to call the constructor.
  • All java classes must have at least one constructor. If you do not explicitly declare any constructor, then on time of compile Java compiler will automatically provide a no-argument constructor i.e also called the default constructor.
  • If you declare any parameterize constructor then that is must write a default constructor.
  • This default constructor calls the parent’s class no-argument constructor i.e super(); or if no parent class extended the called constructor of Object Class i.e directly or indirectly parent class of all the class.

Example of Constructors

//Class Declaration
public class Animal {
	//instance variables
    String name;
    String breed;
    int age;
    String color;

    //Default Constructor : Constructor without parameter
    public Animal()
    {
    this.name="Default";
    }

   // Parameterize Constructor : Constructor with parameter
    public Animal(String name, String breed,
                   int age, String color)
    {
        this.name = name;
        this.breed = breed;
        this.age = age;
        this.color = color;
    }
	//Parameterize constructor
	//Constructor Overriding
	public Animal(String name, String breed)
    {
        this.name = name;
        this.breed = breed;
    } 

}

Object Creation By Constructor

Here you will see both ways to create objects of Animal Class by using the default and parameterize constructors.

public TestClass
{
	public static void main(String[] args)
	{
	 //Instance Default Constructor
	 Animal dog_tommy=new Animal();

	 //Instance with Parameterize Constructor
     Animal dog_tommy=new Animal("Tommy","Small Dog",5,"Black");
	}
}

Does the Constructor return any value?

A constructor doesn’t have return type while implementation, but the constructor returns the current instance of the class. We can write return statements inside the class.

Constructor Overloading

Similar to methods, we can overload constructors also by creating an object in many ways. Java compiler differentiates between these constructors based on signature (i.e numbers, type, and order of parameters).

What is Constructor Chaining?

Constructor chaining is the process of calling a constructor from another constructor for the current object.

Constructor chaining can be performed in two ways:

  • Within the same class: Use this() keyword for same class constructors.
  • From base class: Use super() keyword to call a base class constructor.

Rules of constructor chaining

  • The this() expression should always be the first line of statment in the constructor.
  • There should always be at least one constructor without this() keyword.
  • Constructor chaining can be performed in any order.

Constructor Chaining Example: Within Same Class

Use this() keyword for constructors in the same class. Here you will see the last constructor with two arguments calling the constructor with the keyword this() for four arguments.

//Class Declaration
public class Animal {
	//instance variables
    String name;
    String breed;
    int age;
    String color;

    //Default Constructor : Constructor without parameter
    public Animal()
    {
    this.name="Default";
    }

   // Parameterize Constructor : Constructor with parameter
    public Animal(String name, String breed,
                   int age, String color)
    {
        this.name = name;
        this.breed = breed;
        this.age = age;
        this.color = color;
    }
	//Parameterize constructor
	//Constructor Overriding
	public Animal(String name, String breed)
    {
	   //constructor chaining
	    this(name,breed,1,"black");
    }
}

Constructor Chaining Example: From Base Class

Use super() keyword to call a constructor from the base class. Here Constructor chaining occurs through inheritance. A sub-class constructor’s call the super class’s constructor first so that sub class’s object starts with the initialization of the data members of the superclass. There could be multilevel of classes in the inheritance chain. Every subclass constructor calls up the chain till class at the top is reached.


public class Person{
    private String name;
    protected String citizenship;

    public Person()
    {
    }

    public Person(String name, String citizenship) {
        super();
        this.name = name;
        this.citizenship = citizenship;
    }

    public void print() {
		System.out.println("Citizen:"+ citizenship + ",Name:" + name);
	}

}

 

public class Employee extends Person {
	private int employeeId;
	private String department;
	private int salary;

	public Employee() {

	}

	public Employee(int employeeId, String name, String department, String citizen) {
			}

	public Employee(int employeeId, String name, String department, String citizen, int salary) {
		// super keyword use to call parent constructor
		//constructor chaining to parent class
		super(name, citizen);
		this.employeeId = employeeId;
		this.department = department;
		this.salary = salary;
		System.out.println("Employee Constructor Executed.");
	}

}

What is the use of constructor chaining?

Constructor chaining is the mechanism to perform multiple tasks in a single constructor rather than creating a separate constructor for each task and make their chain. Constructor Chaining makes the program more readable.

Constructors Vs Methods

Constructor Method
Constructor(s) must have the same name as the class within which it defined. The method does not have the same name as the class in which defined.
Constructor(s) does not return any type. method(s) have the return type or void if does not return any value.
A constructor is called only once at the time of Object creation. Method(s) can be called any number of times.
In case constructor not present in class, the default constructor provided by the compiler. In the case of Method, the compiler doesn’t provide the default method.
Constructs invoked implicitly Methods invoked explicitly.
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s