Join
Blogs
Questions
Videos
Tags
Members
Search
 
 
Create your own blog, earn points and get popular!

How to call super class constructor from subclass constructor?

Constructor of the super class can be called using super.

 
  1. public class Q1 {
  2.  Q1(){
  3.   System.out.println("Default Construcotr");
  4.  }
  5.  
  6.  Q1(String msg){
  7.   this(); //calls default constructor
  8.   System.out.println("One Argument Constructor");
  9.  }
  10. }
  11.  
  12. class Q2 extends Q1{
  13.  
  14.  Q2(){
  15.   super();//calls no default constructor of Q1 class.
  16.  
  17.   /*
  18.    * To call super class constructor with arguments, pass same arguments in
  19.    * super.
  20.    *
  21.    * e.g.
  22.    * super("Hello world") will call Q1(String msg) constructor.
  23.    */
  24.  }
  25. }
Please note that, super must be the first statement in the subclass constructor.
Your rating: None Average: 5 (1 vote)
Share this

Post new comment

7 + 4 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.