In constructors of java why this() and super() should be in the first line?

Submitted 3 years, 6 months ago
Ticket #189
Views 211
Language/Framework Java
Priority Medium
Status Closed

Tell me a way..........

Submitted on Oct 03, 20
add a comment

2 Answers

In Java you can put a call to the parent constructor using the keyword super as the first line in a subclass constructor to initialize inherited fields. When to use super keyword :

1) To access the data members of parent class when both parent and child class have member with same name
2) To explicitly call the no-arg and parameterized constructor of parent class) To access the method of parent class when child class has overridden that method.

Example :

//Parent class or Superclass or base class
class Superclass
{
   int num = 100;
}
//Child class or subclass or derived class
class Subclass extends Superclass
{
   /* The same variable num is declared in the Subclass
    * which is already present in the Superclass
    */
    int num = 110;
    void printNumber(){
	System.out.println(num);
    }
    public static void main(String args[]){
	Subclass obj= new Subclass();
	obj.printNumber();	
    }
}

Submitted 3 years, 6 months ago

Thank debasmita for the answer ,but the problem is I want to know why super() and this() are kept as only first statements.

- Soudhamini 3 years, 6 months ago


Verified

The parent class constructor requires to be called before the subclass' constructor. This will assure you that if you call some methods on the parent class in your constructor, the parent class has already been set up correctly.
    So the this() and super() statements should be the first statements

Submitted 3 years, 6 months ago

The answer was helpful thankyou.

- Soudhamini 3 years, 6 months ago


Latest Blogs