Constructor in java - Constructor chaining, access modifiers with constructors, constructor overloading, exception thrown, constructors are not inherited, Difference between constructors and methods


You must have heard a lot about constructor in java, in this post we’ll discuss in detail about constructor.

Constructor in java>
Constructor are used to create object in java.
whenever new keyword is used constructor of class is called to create new object.



  1. Constructor have same name that of class.
public class MyClass {
   MyClass(){} //constructor
}

  1. Constructor do not have any return type.

  1. When no constructor is defined explicitly in the class, compiler implicitly provides no-argument constructor (no-arg constructor) in class.

Let’s say our class is like this -
public class MyClass {
}

compiler will provide default implicit no-arg constructor -
public class MyClass {
    //default implicit no-arg constructor constructor provided by compiler.
   MyClass(){
       super();
   }
}




  1. Constructor chaining - whenever the object of class is created, implicitly default no-arg constructor of class and its super class constructor is called.
Q. But how constructor of superclass is called?
A. Implicitly first statement of constructor is super(), [that means by default first statement of constructor super() is called, super() calls implicit/explicit no-arg constructor of superclass].


Let’s we have superclass and subclass like this -
class SuperClass{
}
class SubClass extends SuperClass{
}



compiler will add default implicit no-arg constructor -
class SuperClass{
   SuperClass(){ //no-arg /no argument constructor
          super();
}
}
class SubClass extends SuperClass{
   SubClass(){
          super();
   }
}




Program - Let’s write these implicit statements explicitly to understand flow -
class SuperClass{
   SuperClass(){
          super(); //will call constructor of java.lang.Object (bcz all classes extend Object)
          System.out.println("constructor of SuperClass");
   }
}
class SubClass extends SuperClass{
   SubClass(){
          super();  //will call constructor of SuperClass
          System.out.println("constructor of SubClass");
   }
  
}
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class MyClass{
   public static void main(String[] args) {
          new SubClass(); //will call constructor of SubClass
   }
}
/* OUTPUT
constructor of SuperClass
constructor of SubClass
*/




  1. Instance variables cannot be accessed in constructor until superclass constructors have been called - Because, as mentioned in above point, superclass constructors are called before constructor of class is executed.



  1. If superclass does not contain no-arg constructor but contain argument constructor.
Than compiler won’t provide no-arg constructor. To avoid compilation error >
  • Solution 1 > subclass must call super(argument) or
  • Solution 2 > declare no-arg constructor explicitly.

Now, we’ll discuss Solution 1 & Solution 2 via program.
class SuperClass{
   SuperClass(int i){ //Argument constructor
     
   }
    
      //Because of argument constructor, compiler won’t provide no-arg constructor
}
class SubClass extends SuperClass{
   SubClass(){
    
   }
  
}

Above code will cause compilation error.
In above code - SuperClass does not contain no-arg constructor but contain argument constructor, so compiler won’t provide no-arg constructor. To avoid compilation error >
  • Solution 1 (Elaboration with program) >subclass must call argument constructor of superClass. Ex - super(argument)
class SubClass extends SuperClass{
SubClass(){
   super(1); //subclass calling argument constructor of superClass
}
}

   Or,

  • Solution 2 (Elaboration with program) > declare no-arg constructor explicitly in SuperClass.  
class SuperClass{
   SuperClass(int i){
     
   }

     //no-arg constructor explicitly in SuperClass
   SuperClass(){
     
   }



}



  1. First line in constructor can either be super() or this(). But, super() and this() cannot be used in same constructor. (Please ensure that super() or this() whichever is used must be be first line of constructor, else you will face compilation error)
We read in above points that compiler implicitly adds super() as first line of constructor, but if we add this() explicitly than compiler doesn’t add super()

Program to understand usage of this() and super() in constructor and also to show this() and super() cannot be used in same constructor >
class SuperClass{
   SuperClass(){
         System.out.println("no-arg constructor of SuperClass");
   }
}
class SubClass extends SuperClass{
   SubClass(){
          this(1);
          System.out.println("no-arg constructor of SubClass");
   }
   SubClass(int i){
          super();
          System.out.println("int-arg constructor of SubClass");
   }
  
}
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class MyClass{
   public static void main(String[] args) {
      new SubClass(); //will call constructor of SubClass
   }
}
/* OUTPUT
no-arg constructor of SuperClass
int-arg constructor of SubClass
no-arg constructor of SubClass
*/


  1. Constructor can use access modifiers like - private, protected and public. If no access modifier is defined than its default.
  • private constructor can be used in Singleton classes where object of the class cannot be created outside class.
  • class with protected constructor cannot be instantiated in other package. Though constructor can be called through inheritance.

 
public class MyClass {
   private MyClass(){} //private constructor
}
public class MyClass {
   MyClass(){} //default constructor
}
public class MyClass {
   protected MyClass(){} //protected constructor
}
public class MyClass {
   public MyClass(){} //public constructor
}



  1. Constructor is not a keyword in java.

  1. Interface does not have constructor in java.

  1. Constructors are never inherited and hence cannot be overridden.


  1. Constructors can be overloaded.
Program to overload constructors >
public class MyClass {
   MyClass(){ //constructor
          System.out.println("constructor");
   }
   MyClass(Integer i){ //overloaded constructor
          System.out.println("overloaded constructor");
   }
  
   public static void main(String[] args) {
          MyClass obj1=new MyClass();
          MyClass obj2=new MyClass(1);
   }
}
/* OUTPUT
constructor
overloaded constructor
*/



  1. Abstract class also have constructor, and those constructors are called when object of concrete subclass is created, because abstract class cannot be instantiated directly.
abstract class AbsClass{
   AbsClass(){
          System.out.println("AbsClass constructor");
   }
}
public class SubClass extends AbsClass{
   SubClass(){
          System.out.println("constructor");
   }
  
   public static void main(String[] args) {
          AbsClass obj1=new SubClass();
   }
}
/* OUTPUT
AbsClass constructor
constructor
*/


any attempt to create object of abstract class will generate compilation error.
AbsClass obj=new AbsClass(); //compilation error



  1. If constructor throws >

  • CompileTime/checked Exception - It must be caught at time of object creation, or method in which object is created must throw appropriate Exception.

Example >

Let’s say constructor throws java.lang.Exception (unchecked)


public class MyClass {
   //constructor
   MyClass() throws Exception{
   }
}

Then,
Method in which object is created must throw appropriate Exception.

/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class MyClass {
  
   //constructor
   MyClass() throws Exception{
   }
  
   public static void main(String[] args) throws Exception {
          MyClass obj1=new MyClass();
   }
  
}



Or,
It must be caught at time of object creation  using try-catch block.
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class MyClass {
  
   //constructor
   MyClass() throws Exception{
   }
  
   public static void main(String[] args) {
          try {
                 MyClass obj1=new MyClass();
          } catch (Exception e) {
                 e.printStackTrace();
          }
   }
  
}


Difference between constructors and methods

constructors
methods
Constructors have same name as that of class.
Methods can have same name as that of class, but generally it is bad practice.
Constructor do not have any return type.
Methods have any return type.

It method does not return anything its return type is void.
Constructor chaining - whenever the object of class is created, implicitly default no-arg constructor of class and its super class constructor is called.
Methods does not have any such chaining.
First line in constructor can either be super() or this()
There is no such compulsion with methods.
Constructors are never inherited and hence cannot be overridden.
Methods are inherited and hence can be overridden.



RELATED LINKS>


Labels: Core Java
eEdit
Must read for you :