Constructors cannot be inherited in JAVA

Although a subclass inherits all of the method and variables from a parent class, it does not inherit constructors.
There are only two ways in which a class can gain a constructor; either you write the constructor, or, because you have not written any constructors, the class has a single default constructor. A parent constructor is always called to a child constructor. Like methods, constructors can call non-private constructors of its immediate superclass.
Often you define a constructor that takes arguments and you want to use those arguments to control the construction of the parent part of an object. You can invoke a particular parent class constructor as part of a child class initialization by using the keyword super from the child constructor’s first line. To control the invocation of the specific constrictor, you must provide the appropriate arguments to super ( ). When there is no call to super with arguments, the parent constructor with zero arguments is called implicitly. In this case, if there is no parent constructor with zero arguments, a complier error results.
The call to super ( ) can take any number of argument appropriate to the various constructors available in the parent class, but it must be the first statement in the constructor.

2 comments:

amar said...

what is the perfect reason behind writing the super keyword as a very first statement in a perticular block

Wicky101 said...

super is used where the same method name present in the parent class is present in the child class and you want to use the one in the parent class from the child class.

class A {
public void add(){}
}
class B extends A{
public void add(){}
//if u want to use the add() of the parent class
super.add();
}
public static void main(String[] args){
B b = new B();
b.add();
}