How are this() and super() used with constructors

This() is used to invoke a constructor of the same class. super() is used to invoke asuperclass constructor.

Showing Answers 1 - 3 of 3 Answers

vegetto

  • Jun 15th, 2008
 

this() is used to specify the current class or the child's class constructor always
and super() refers to the parent's class constructor

To use them follw the rules:

super()has to be the first line in any case if you are using the parent's class constructor in the child's class because your code might be using the parent's class variable and usng super() in the midway doesn't make any sense.So it has to be the first line always in the child's constructor.you can also supply super with arguments if ur parent class  has defined such constructor

this() also has to be the first line and is generally used when u r using the concept of constructor overloading then suppose u have 2 constructors eg:

public class Manager extends Employee
{ private String department;
   
     public Manager(String name,double salary)
    {
       super(name,salary); // always first line
         
    }
    public Manager(String name,String dept)
    {
        this (name,dept) // always first line and this refers to above const.
         department=dept;
    }
}
 use this() and super() as shown above
and note that whatever happens the constructor of the parent class will always be executed first and then child's class 

  Was this answer useful?  Yes

Give your answer:

If you think the above answer is not correct, Please select a reason and add your answer below.

 

Related Answered Questions

 

Related Open Questions