top of page
hand-businesswoman-touching-hand-artificial-intelligence-meaning-technology-connection-go-

Constructors in Java

A constructor has the code that runs when we instantiate an object. In other words, the code that runs when we say new on a class type.

Every class we create has a constructor, even if we don’t write it yourself.


Duck myDuck = new Duck();

A constructor does look and feel a lot like a method, but it’s not a method. It’s got the code that runs when we say new. In other words, the code runs when we instantiate an object.

The only way to invoke a constructor is with the keyword new followed by the class name. JVM finds the class and invokes the constructor in that class.

Every class including abstract class MUST have a constructor. We can write constructor for our class, but if we don’t then compiler writes one for us. A compiler’s default constructor looks like this:


class Shape{   
public Shape(){ } //The constructor for the Shape class
}

Two Key points to remember about constructors are:

Constructors do not have any return type
Constructors name must be exactly same as the class name and it’s mandatory

Constructors are used to initialized instance variable as follows:


public class Shirt{  
int size;  
String color;  
public Shirt(String color, int size){ 
     this.color = color;      
	 this.size = size;  
} 
public static void main(String[] args) {  
Shirt s = new Shirt(); //Won't compile,no matching constructor
Shirt s = new Shirt("blue",42);//No problem,Arguments match the 			Shirt constructor 
}
}

In the above code, the Shirt class does not have a no argument constructor. So the following code will fail to compile:


Shirt s = new Shirt(); //Won't compile,no matching constructor

but the following code will compile as the arguments match with the constructor:


Shirt s = new Shirt("blue",42);//No problem,Arguments match the Shirt constructor

Constructors can be overloaded.So it’s very common (and desirable) for a class to have a no-arg constructor, regardless of how many other overloaded constructors are in the class.


Constructor Chaining


Constructors are invoked at runtime when you say new on some class type as follows:


Circle c = new Circle();

Let’s assume Circle extends Shape and Shape extends Object class . Now what really happens when we say new Circle() ?

  1. Circle constructor is invoked. Every constructor invokes the constructor of its superclass with an (implicit) call to super(), unless the constructor invokes an overloaded constructor of the same class

  2. Shape constructor is invoked. Shape is the superclass of Circle.

  3. Object constructor is invoked . Object is the ultimate superclass of all classes, so class Shape extends Object even though we don’t actually type “extends Object” into the Shape class declaration. It’s implicit. At this point we’re on the top of the stack.

  4. Object instance variables are given their explicit values. By explicit values, we mean values that are assigned at the time the variables are declared, like “int x = 27”, where “27” is the explicit value (as opposed to the default value) of the instance variable

  5. Object constructor completes.

  6. Shape instance variables are given their explicit values (if any).

  7. Shape constructor completes.

  8. Circle instance variables are given their explicit values (if any).

  9. Circle constructor completes.



Rules for Constructors


  • Constructors can use any access modifier, including private. A private constructor means only code within the class itself can instantiate an object of that type.

  • The Constructor name must match the name of the class.

  • Constructors must not have a return type.

  • If we don’t type a constructor into your class code, a default constructor will be automatically generated by the compiler.

  • The default constructor is ALWAYS a no-arg constructor.

  • If we want a no-arg constructor and we’ve typed any other constructor into our class code, the compiler won’t provide the no-arg constructor (or any other constructor) for us. If we’ve typed in a constructor with arguments, we won’t have a no-arg constructor unless we type it in ourself!

  • First statement of every constructor is either a call to an overloaded constructor (this()) or a call to the superclass constructor (super()). This call can be inserted by the compiler.

  • If we write a constructor and if we do not call super() or call this(), the compiler will insert a no-arg call to super() as the very first statement in the constructor.

  • A call to super() can be either a no-arg call or can include arguments passed to the super constructor.

  • A no-arg constructor is not necessarily the default (compiler-supplied) constructor, although the default constructor is always a no-arg constructor.

  • a call to an instance method, or access an instance variable can not be made until after the super constructor runs.

  • Only static variables and methods can be accessed as part of the call to super() or this().

  • Interfaces do not have constructors. Interfaces are not part of an object’s inheritance tree.

  • Abstract classes have constructors, and those constructors are always called when a concrete subclass is instantiated.

  • Calling a constructor is illegal.The only way a constructor can be invoked is from within another constructor. We can’t write code that actually calls a constructor as follows:

class Shape {      
Shape() { } // constructor      
void doStuff() {        
Shape();  // calling the constructor - illegal!      
}
}

The compiler will generate a default constructor for the class below, because the class doesn’t have any constructors defined.


class Shape { }

Compiler will not generate any default constructor for the class below as it already has constructor.


class Shape {   
Shape(String name) { }
}

Let’s analyze the code below:


class Shape {   
void Shape() { } //it's a method not constructor
}

Compiler will generate constructor for the above class as it does not have any constructor.

“ void Shape() { }” is simply a method that happens to have the same name as the class.

Remember that, Constructor must not have a return type.


Default Constructor (compiler generated) properties:


  • The default constructor has the same access modifier as the class.

  • The default constructor has no arguments.

  • The default constructor includes a no-arg call to the super constructor (super()).

If we write a class like below


class Shape { }

Then the compiler generated constructor code will be:


class Shape {   
Shape() {      
super();   
}
}  

The code below will not work as the Circle constructor will invoke a no-argument Shape() constructor, but there isn’t one.


Class Shape{   
Shape(String color){    }
}
Class Circle extends shape{
// Constructor identical to compiler-supplied
// default constructor   
Circle(){      
	super(); // Won't work!Invokes a no-arg Shape() constructor,but 		there isn't one!    
	}
}

Constructors are never inherited. They aren’t methods. They can’t be overridden because they aren’t methods and only instance methods can be overridden. Although constructors can’t be overridden, they can be overloaded.


Overloaded Constructor


Overloading a constructor means typing in multiple versions of the constructor, each having a different argument list like below:


class Shape {     
Shape() { }     
Shape(String color) 
{ }  
}

The preceding Shape class has two overloaded constructors, one that takes a string, and one with no arguments. Because there’s no code in the no-arg constructor, it’s actually identical to the default constructor the compiler supplies, but since there’s already a constructor in this class the one that takes a string, the compiler won’t supply a default constructor.


In summary, A constructor is always invoked when a new object is created. Every class even an abstract class has at least one constructor. Constructor must have the same name as the class and Constructor must not have a return type.


Hope you find this blog helpful in learning the concept of Constructor in JAVA.

Thanks for reading.



21 views0 comments

コメント

5つ星のうち0と評価されています。
まだ評価がありません

評価を追加
bottom of page