BIG
DATA

JAVA

CONSTRUCTOR IN JAVA

Read more about »
  • Java 9 features
  • Read about Hadoop
  • Read about Storm
  • Read about Storm
 

Quick Links within the page



Before we start with constructors we will go through something called 'Access Modifiers'.

Access Modifiers

The access modifiers in java specifies accessibility or scope of a data member, method, constructor or class. There are 4 types of java access modifiers:

  • private
  • default or package-private (no explicit modifier)
  • protected
  • public
private access modifier

The private access modifier is accessible only within class. Methods, Variables and Constructors that are declared private can only be accessed within the declared class itself. Code inside subclasses cannot access the variable or method, nor can code from any external class.
Private access modifier is the most restrictive access level.
Classes and Interfaces cannot be private. If a class or interface is marked as private then no external class can access the class or interface. This doesn't really make sense for classes though. Therefore, the access modifier private is mostly used for fields, constructors and methods.

class A{  
	private int data = 10;  
	private void displayData(){
		System.out.println("Data:=" + data);	//can be accessed within class
	} 
}  
  
public class Demo{  
	public static void main(String args[]){  
		A obj = new A();  
		System.out.println(obj.data);	//Compile Time Error  
		obj.display();	//Compile Time Error  
	}  
}  

In the above example, I have created 2 classes 'A' and 'Demo'. 'A' class contains private data member and private method. In class 'A', 'displayData' method can access 'data' variable but when Demo clas is trying to access We will get compile time error because we are accessing these private members from outside the class.

[Note]: Class cannot be private or protected except nested class.

default access modifier

If you don't use any modifier, it is treated as default modifier. The default modifier is accessible only within package. Default access levels means that code inside the class itself plus code inside classes in the same package as this class. It is also called as package-private or no explicit modifier or package access modifier.

Subclasses cannot access methods and member variables in the superclass, if they have default accessibility declared, unless the subclass is located in the same package as the superclass.

public class A {
    int data = 10;
}

public class B {
    A obj = new A();

    public int getData{
        return obj.data;
    }
}

The 'B' class above can read the 'data' member variable of A's object, provided that 'A' and 'B' are located in the same package.

[Note]: packages are named groups of related classes

protected access modifier

The protected access modifier is accessible within package and outside the package but through inheritance only. That is accessible by all the child classes and also by all the classes within the same package.

The protected access modifier can be applied on the data member, method and constructor. It can't be applied on the class

public class A {
    protected int data = 10;
}

public class B {
    A obj = new A();

    public int getData{
        return obj.data;
    }
}

The 'B' class above can read the 'data' member variable of A's object, provided that 'A' and 'B' are located in the same package. But lets have class 'C' which is not in the same package nor a child class of 'A'.

public class C {
    A obj = new A();

    public int getData{
        return obj.data;	//compile time error
    }
}

The 'C' class cannot access data variable of A's object since it is beyond the scope.

public access modifier

The public access modifier is accessible everywhere. No restriction modifier.

A class, method, constructor, interface etc declared public can be accessed from any other class. Therefore fields, methods, blocks declared inside a public class can be accessed from any class belonging to the Java world.

However if the public class we are trying to access is in a different package, then that public class needs to be imported.

public class A {
    public int data = 10;
}

public class B {
    A obj = new A();

    public int getData{
        return obj.data;
    }
}

The 'B' class can access the data field in 'A' no matter what package the 'B' is located in, because both the class are declared public.

Modifier Class Package Subclass World
public Y Y Y Y
protected Y Y Y N
no modifier Y Y N N
private Y N N N


Constructors

A class contains constructors that are invoked to create objects from the class blueprint. Constructors have one purpose in life: to create an instance of a class. This can also be called creating an object.

Constructor in java is a special type of method that is used to initialize the object. Constructor is invoked at the time of object creation. It constructs the values i.e. provides data for the object that is why it is known as constructor. Typically the constructor initializes the fields of the object that need initialization. Constructors also takes parameters, so fields can be initialized in the object at creation time.

So Defintiion: Constructor is a special type of method that is used to initialize the object.

Defining a Constructor

Constructor declarations look like method declarations except that they use the name of the class and have no return type. For example:

public class Car {
    public Car() {
	System.out.println("Car is created");
    }
}

public class Demo {	
	Car myCar = new Car();		//constructor is called here
}
Output:
Car is created

In this example, we are creating the no-arg constructor in the Car class. It will be invoked at the time of object creation.
This is part which defines the constructor:

public Car() {
	System.out.println("Car is created");
}

First, an access modifier is written. These have the same meanings as for methods and fields. They determine what classes can access or call the constructor.

Second, the name of the class is used as the name of the constructor method. This signals to the Java compiler that this is a constructor. Also notice that the constructor has no return type, like ordinary methods have.

Third, a list of parameters are declared inside the parentheses () . In the example above no parameters are declared. In the next section I will show an example of a constructor with parameters.

Fourth, the body of the constructor is defined inside the curly brackets { }. In the example above I have added a simple print statement.

Parameterized Constructor

A constructor with parameters is known as parameterized constructor.


public class Car {
    public Car(String name) {
		System.out.println(name + " is created");
    }
}

public class Demo {	
	Car myCar = new Car("BMW");		//constructor is called here
}
Output:
BMW is created

In this example, we are creating the parameterized constructor in the Car class. Again it will be invoked at the time of object creation.

Default Constructor

If a programmer forgets to write constructor or skips writing because of his laziness, compiler automatically creates a constructor called default constructor. Thus, once the class is compiled it will always have at least a no-argument or default constructor.

If you do define a constructor for your class, then the Java compiler does not insert the default no-argument constructor into your class.

If there is no constructor in a class then compiler automatically creates a default constructor like below:

According to Java doc :If a class contains no constructor declarations, then a default constructor with no formal parameters and no throws clause is implicitly declared.

default constructor

Now you could ask, What is the purpose of default constructor?

Answer is Default constructor provides the default values to the object like 0, null etc. depending on the type. Check in the below example:


public class Car {
	String name;
	int mileage;
	
	void display(){
		System.out.println("Name: " + name);
		System.out.println("Mileage: " + mileage);
	}
}

public class Demo {	
	Car myCar = new Car();
	myCar.display();
}
Output:
Name: null
Mileage: 0

In the above Car class,I have not created any constructor so compiler provides me a default constructor.Here 0 and null values are provided by default constructor.

Constructor Overloading

A class can have multiple constructors, as long as they differ in their parameter list(signature). You can define as many constructors as you need.This is called as Constructor overloading.


public class Car {
	public Car(){
		System.out.println("default car is created");
	}
	
    public Car(String name) {
		System.out.println(name + " is created");
    }
}

public class Demo {	
	Car myCar = new Car();		//First constructor is called here
	Car myCar = new Car("BMW");		//Second overloaded constructor is called here
}
Output:
default car is created
BMW is created

Constructor questions

Now you may be having quite a few questions about Constructor. Please contact me or you can leave it in comment section. For more questions on constructor please go to 'Interview section' of oopguru.

[Q] Does constructor return any value?
You may ask constructor does not have a return type then what its job is only to initialize the ojects?.
Answer is constructor returns class instance along with initialization of objects.

[Q] What else constructor can do apart from initialization?
Constructor can create object, start a thread, call other methods etc. You can perform any operation just like you do in the method.



Constructor Chaining

You can call one constructor from another one within same class or of its subclasses. This is known as Constructor Chaining.

'this' and 'super' keyword is used to call one constructor from other in Java. this() can be used to call other constructor of same class while super() can be used to call constructor from super class in Java.

"this" and Constructor

Constructors and methods use the keyword 'this' quite differently. A method uses this to refer to the instance of the class that is executing the method.Whereas Constructors use 'this' to refer to an overloaded constructor that is another constructor in the same class with a different parameter list.


public class Car {
    public Car(String name) {
		System.out.println(name + " is created");
    }
	
	public Car(){
		this("Ford");
	}	
}

public class Demo {	
	Car myCar = new Car();
	Car myCar = new Car("BMW");
}
Output:
Ford is created
BMW is created

In the above code, there are two constructors. The first takes a String input to name the car. The second, taking no parameters, calls the first constructor by the default name "Ford".

If a constructor uses this, it must be in the constructor's first line; ignoring this rule will cause the compiler to object.



"super" and Constructor

Again methods and constructors both use 'super' to refer to a superclass, but in different ways.Methods use super to execute an overridden method in the superclass.

Constructors use super to invoke the superclass's or baseclass's constructor. If a constructor uses super, it must use it in the first line; otherwise, the compiler will throw exception.

class Parent {
	Parent() {
    	System.out.println("Parent constructor");
    }
}
class Child extends Parent {
       Child() {
               super();
               System.out.println("Child constructor");
       }
}

class demo {
	Child child = new Child();
}
Output:
Parent constructor
Child constructor

Lets see what happens if I remove super() from childs constructor.

class Parent {
	Parent() {
    	System.out.println("Parent constructor");
    }
}
class Child extends Parent {
       Child() {
           System.out.println("Child constructor");
       }
}

class demo {
	Child child = new Child();
}
Output:
Parent constructor
Child constructor

You're kidding! SAME output.What is the use of super keyword then.And what really happened here?

From above, its very clear that super() is added in each class constructor automatically by compiler.That is why same output.For the next question of its usage, lets see below code:

class Parent {
	Parent() {
    	System.out.println("Parent constructor -1");
    }
    
	Parent(int i) {
    	System.out.println("Parent constructor -2");
    }
}
class Child extends Parent {
       Child() {
               super(5);
               System.out.println("Child constructor");
       }
}

class demo {
	Child child = new Child();
}
Ouput:
Parent constructor -2
Child constructor

So 'super' is useful when you have more than one constructor(overloaded) in superclass and you want to call a specific constructor in child class's constructor, you use 'super' keyword.

Why super() ?
Class can be determined not only by state and behavior but also by each of its superclasses. Due to that reason it is not sufficient to execute a constructor of that class but also need to initialize each constructor of superclasses.

A superclass constructor must execute before a subclass constructor. So that the state and behavior defined by the superclass may be correctly and completely initialized before a subclass constructor executes.



Access modifiers and constructor

Let us discuss about access modifiers used along with constructors.We know what are the differnet modifiers in Java. Let us take one by one:

public: If you declare constructor as public, any other class can instantiate this class.

protected: If you declare constructor as protected, any other child classes or classes within the same package can instantiate this class.

First two modifiers were simple and clear to understand. Well the next two gets little tricky.

default or package-private: For this, Well it depends on class access modifier declaration.

  • if the class is declared public, then the default constructor is implicitly given the access modifier public;
  • if the class is declared protected, then the default constructor is implicitly given the access modifier protected;
  • if the class is declared private, then the default constructor is implicitly given the access modifier private; otherwise,
  • the default constructor has the default access implied by no access modifier.

Huh! well this was not that tricky, lets take a look at private constructor.

private: If you declare constructors as Private then it prevents a class from being explicitly instantiated by its callers. Scroll down for More about this.

Private constructor

If you declare constructors as Private then it prevents a class from being explicitly instantiated by its callers.
Following are two categories or cases where a private constructor can be useful:

  • Object construction is forbidden
  • Object construction is private only
Object construction is forbidden

If a class offers only static members then construction or instantiation of that class is of no use. In this case we can forbid object construction.How to acheive this, yes you guessed it correctly by having private constructor.

If the programmer does not provide a constructor for a class, then a default constructor with no formal parameters and no throws clause is implicitly declared. To stop compiler from doing this, just add a private no-argument constructor to the class. This constrctor may be empty.

Object construction is private only

Sometimes a case may be: Objects can be constructed, but only internally. How to acheive this. And again you guessed it correctly, by having private constructor.

While software designing we may come across situation like only one object of the class should exist. Creation of multiple objects of that class is forbidden. How to acheive this. And again for the love of god, you guessed it correctly, by having private constructor.

How to implement it? Tricky isn't it. Don't worry let me explain:

public class Car {
   private static Car instanceCar = null;
   private Car() {
	  // private constructor
	  System.out.println("constructor is called");
   }
   public static Car getInstance() {
	  if(instanceCar == null) {
		  instanceCar = new Car();
	  }
	  return instanceCar;
   }
}

private constructor And now if you write like this, compiler will not be happy saying Constructor Car() is not visible and ask us to change visiblity. But we dont want to do it. That is why we have static method called getInstance().We will learn about static later. We will modify the code like this:

class demo {
	Car myCar = Car.getInstance();
}
Output:
constructor is called

We could call getInstance() method without creating object of Car class, because we have declare method as 'static'. getInstance() method creates a new instant of class, as it can access private constructor being in same class and refernces it to myCar refernce. Now we will check whether only one instance is created or not.

class demo {
	Car myCar = Car.getInstance();
	Car myCar2 = Car.getInstance();
	Car myCar3 = Car.getInstance();
}
Output:
constructor is called

What you dont believe me? Go try yourself in eclipse.This works because of this code:

if(instanceCar == null) {
    instanceCar = new Car();
}
return instanceCar;


Difference between Constructor and Methods

Java ConstructorJava Method
Constructor is used to initialize the state of an object.Method is used to group java statements and expose behaviour of an object.
Constructor is invoked implicitly.Method must be explicitly invoked.
No return type.Method must have return type.
Constructors are not inherited. Methods are inherited.
Java compiler provides a default constructor if you don't.Methods are not provided by compiler in any case.
Constructor name must be same as the class name. Method name can be any.