I am a beginner in java programming language, recently I have studied that constructors can not be inherited in java, Can anyone please explain why?
I have already read this link of C++
No, constructors cannot be inherited in Java. In inheritance sub class inherits the members of a super class except constructors. In other words, constructors cannot be inherited in Java therefore, there is no need to write final before constructors.
Constructors are different from other class methods in that they create new objects, whereas other methods are invoked by existing objects. This is one reason constructors aren't inherited.
A parent class constructor is not inherited in child class and this is why super() is added automatically in child class constructor if there is no explicit call to super or this.
Constructors are not inherited. The superclass constructor can be called from the first line of a subclass constructor by using the keyword super and passing appropriate parameters to set the private instance variables of the superclass.
In simple words, a constructor cannot be inherited, since in subclasses it has a different name (the name of the subclass).
class A { A(); } class B extends A{ B(); }
You can do only:
B b = new B(); // and not new A()
Methods, instead, are inherited with "the same name" and can be used.
As for the reason: It would not have much sense to inherit a constructor, since constructor of class A means creating an object of type A, and constructor of class B means creating an object of class B.
You can still use constructors from A inside B's implementation though:
class B extends A{ B() { super(); } }
What you are talking about is Java language level. If constructors were inherited, that would make impossible to make class private. As we know method visibility can't be downgraded. Object
class has a no argument constructor and every class extends Object
, so in case of constructor inheritance every class would have a no argument constructor. That breaks OO principles.
Things are different on bytecode level. When object is created, two operators are called:
We can modify bytecode so that memory is allocated for Child class and constructor is called from Parent class. In this case we can say that constructors are inherited. One notice if we don't turn off byte code verification, JVM will throw an exception while loading class. We can do this by adding -noverify
argument.
Conclusion:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With