Hey Guys, I am creating this blog to share deep knowledge in Java, JSP, Servlets, JDBC, Hibernate, Spring and Spring MVC in details.

Why Constructors are not inherited in Java?


Why Constructors are not inherited in Java?
Constructor is a block of code that allows you to create an object of the class and has the same name as a class with no explicit return type.
Whenever a class (child class) extends another class (parent class), the subclass inherits state and behavior in the form of variables and methods from its superclass but it does not inherit constructor of superclass because of following reasons:
Constructors are special and have the same name as the class name. So if constructors were inherited in child class then child class would contain a parent class constructor which is against the constraint that constructor should have the same name as the class name.
class Parent {
            public Parent() {
            }

            public void print() {
            }
}
public class Child extends Parent {
            public Parent()
    {
    }
            public void print() {
            }
public static void main(String[] args) {
  Child c1 = new Child(); // allowed
  Child c2 = new Parent(); // not allowed
            }
}
If we define Parent class constructor inside Child class it will give compile time error Return type for the method is missing and consider it a method. But for print method it does not give any compile time error and consider it an overriding method.
Now suppose if constructors can be inherited then it will be impossible to achieving encapsulation. Because by using a super class’s constructor we can access/initialize private members of a class.
A constructor cannot be called as a method. It is called when object of the class is created so it does not make sense of creating child class object using parent class constructor notation. i.e.
 Child c = new Parent();
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.


Share:

Related Posts:

No comments:

Post a Comment

Popular Posts