| |
GeekInterview.com > Interview Questions > J2EE > Java
| Print | |
Question: How are this() and super() used with constructors
Answer: this() is used to invoke a constructor of the same class. super() is used to invoke asuperclass constructor. |
| June 06, 2008 09:11:09 |
#1 |
| vegetto |
Member Since: June 2008 Total Comments: 10 |
RE: How are this() and super() used with constructors |
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 |
| |
Back To Question | |