Constructors cannot be inherited, basically a constructor is not a method.
Constructors are used to give a valid state for an object at creation.
I am wondering what benefit it would be by inheriting constructors? If you have the answer them pls let me know. All you need to do is give an explicit call.
Even if they are inherited how would you call the inherited constructor while creating the object? It would look like you are creating the object of superclassthough what you want is an object of the sub-class. You can get an idea of what I am telling
by looking below.
class A{
A(){
/*do something*/
}
}
class B extends A{
B(){
/*do something*/
}
public static void main(String[] args){
A a = new A();
B b = new A();//is'nt this confusing?
}
B b = new A();--->Since your class B inherits
the constructor of class A why not use it? Now I hope you see what happens if constructors are inherited.
It is the responisiblity of the programmer to see to it that the variables of the superclass have a valid value before the creation of the subclass object. Though constructors are not inherited the no-arg super class constructor is called by default if the first
statement of your sub-class constructor is not a call to a super calls constructor or a constructor of the same class.
Author : Vinay.
Comments
Post a Comment