48

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++

Steve Chambers
  • 37,270
  • 24
  • 156
  • 208
Mayank Tiwari
  • 2,974
  • 5
  • 30
  • 52

12 Answers12

46

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(); }
}
Lake
  • 4,072
  • 26
  • 36
  • Define "inheriting". Doesn't inheriting means that you could "USE" it. So you basically inherit constructors ? – Paweł Brewczynski Nov 15 '13 at 10:47
  • 1
    As far as my explanation is concerned, "inheriting" means that you can use method X inherited by class B from class A PUBLICLY (i.e. outside class B's constructor scope), for example B b = new B(); b.X(); You cannot do B b = new A(); so you could not publicly use "inherited constructors" even if you'd declare them public, even inside class B. If you think being able to call constructor A inside B's constructor means inheritance, then inheritance be it ^^ – Lake Mar 20 '14 at 02:54
  • Now I know "why", but I still wish there were some syntax sugar to eliminate those constructors that just call parent's constructors with the same arguments. – Damn Vegetables Dec 10 '15 at 16:03
  • 2
    "a constructor cannot be inherited, since in subclasses it has a different name" - what language a design choice! ROTFL. We wanted to make classes hard to inherit and hard to refractor, and constructors hard to write. Either that or they were just so in love with this idea of self-named constructors that they refused or never thought to rename them. We did it this way so it must continue forever as tradition. – user1122069 Mar 01 '16 at 20:38
  • I think it's actually quite reasonable of a choice to let the constructors have their defining class' name, defining a constructor that just calls super with the same arguments doesn't look like hard work for me.. there might be better way to design the language though. – Lake Mar 03 '16 at 10:06
  • It is a hard work for me because my superclass has a parameterized constructor which constructs the object through reflection. That means subclasses don't need to do anything even if they have different member fields that should be initialized. Despite this fact, the subclasses have to implement their own constructors only to call `super(...)`. If you have dozens of such subclasses, this will be an overhead. – Aetherus Jun 22 '16 at 03:57
  • 1
    The parent class constructor is by default called from the child class constructor. – Amal lal T L Aug 06 '18 at 17:00
  • You're right, I failed to mention that. Only if it doesn't have any arguments. – Lake Aug 07 '18 at 12:52
  • I find that in the case of custom exceptions, one usually want to have all the same constructors as the base class, so in these circumstances, it would make sense for java to generate default constructors which all call super by default, when no constructors are provided. – Gzorg Mar 28 '19 at 14:46
  • Not being able to initialize a reference to Derived with a reference to Base has exactly nothing to do with inheriting constructors. How constructors are named has the same non-relationship to their inheritability. No wonder this won the prize. – Deduplicator Dec 23 '21 at 18:07
23

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:

  1. new - allocates memory for object
  2. invokespecial - calls constructor on newly allocated piece of memory

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:

  1. Constructors are not inherited on language level due to OO principles
  2. Constructors are inherited on bytecode level
Yogesh Umesh Vaity
  • 41,009
  • 21
  • 145
  • 105
Mikhail
  • 4,175
  • 15
  • 31
  • When you say the constructors are inherited at bytecode level, I assume that is not the default and that happens only if we explicitly modify `invokespecial` to call parent constructor. Please confirm. – Kannan Ramamoorthy May 03 '22 at 06:06
14

Reason mentioned in docs of Inheritance

A subclass inherits all the members (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.

You can refer docs of Providing Constructors for Your Classes

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307
  • 2
    sir I have also read this, constructors are special member functions of a class whose name is same as that of class, but they do not have any return type. Is it TRUE? – Mayank Tiwari Aug 09 '13 at 13:31
  • 2
    @user2320537 If you mean `data type` means `return type`, yes they don't have any `return type`. – Suresh Atta Aug 09 '13 at 13:34
4
  • A constructor may only be called with new. It cannot be called as a method.
  • The constructor name is identical to the class name.

So inheritance is practically not possible as such. However in a construct one might call other constructors.

  • In the same class using this(...);
  • Of the extended class using super(...);

Example

class A {
    A() { }          // Constructor
    A(int a) { }     // Constructor
    A(boolean c) { } // Constructor
}
class B extends A {
    B() {
        this(3, 7);
    }
    B(int a) {
        super();
    }
    B(String b) {
        super(7);
    }
    B(int a, int c) { // Calls super() implicitly
    }
}
A a = new B(8):

There unfortunately is no possibility to use A's constructor for a boolean:

B b = new B(true): // ERROR

The language designes could have implemented such a thing as:

Generate for every public constructor in the base class, a constructor with the same signature if such a constructor is not defined already. Call super with the same parameters. Call this() if there is a default constructor.

That seems a bit bloating the code. And is not simply a pointer in a virtual method table, by which method inheritance/overriding works.

Joop Eggen
  • 107,315
  • 7
  • 83
  • 138
3

Constructors are not members of classes and only members are inherited. You cannot inherit a constructor. That is, you cannot create a instance of a subclass using a constructor of one of it's superclasses.

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
2

Simple answer I observed, You cannot invoke or use constructors of parent class in child class directly but methods of parent class you can use directly in child class.

In case you have method in child class with same name as in parent class at that time only you need to use "super" keyword to invoke parent class method resolve call ambiguity.

"To invoke" parent class constructor in child class you always need "super" keyword. So parent class constructors are "not directly available" like parent class methods in child class so we can say constructors can not be inherited.

Nikhil
  • 21
  • 1
2
  1. 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 same name as class name.
  2. However, parent class constructor can be called from child class constructor using super().

An example code to demonstrate the concept.

class Base{
   public void Base()
   {
       System.out.println("Inside Base class constructor");
   }
}
class Derived{
   public void Derived()
   {
       super();
       System.out.println("Inside Derived class constructor");
   }
class mainClass{
   public static void main(String args[])
   {
       Derived obj = new Derived();
   }


Output:
Inside Base class constructor
Inside Derived class constructor
1

No, constructors will not be inherited to subclass, eventhough its a non-static member it will not be inherited to subclass because constructors will not be loaded inside the object, it is used to create the object. Constructors are like a non-static initializer

Ashwini E
  • 9
  • 1
1

Only fields, methods, and nested classes are the membe of any class not Constructors. A subclass inherits all the members like (fields, methods, and nested classes) from its superclass. Constructors are not members, so they are not inherited by subclasses, but the constructor of the superclass can be invoked from the subclass.

1

Syntactic limitations can often be circumvented should there be any reason for a feature in a conceptual way. With this, I believe, the real reason for not supporting inheritance of constructor is not due to syntactic limitations but rather due to semantics.

Conceptually inheritance provides a mechanism to acquire (or inherit) a behavior and most likely without writing any piece of code since its purpose is to provide code-reuse. For a child class, it makes no case to inherit the behavior of initialization of its parent class. After all, an inherited behavior finds its best use when an external caller can use it without knowing who (in the parent chain) actually has implemented it. As you can see, a caller hardly has any business knowing how a parent class is initialized via its child class, there is no discernible reason for supporting inheritance for a (parent class’s) constructor.

KGhatak
  • 6,995
  • 1
  • 27
  • 24
1

you can't inherited constructors but you can inherit initialized value in constructor like

class test1 {
    int a,b;
    test1(){
        a = 100;
        b = 20;
    }
}

class test2 extends test1 {
    test2(){
        // do something
    }
}

class test {
    public static void main(String[] args) {
        test2 t = new test2();
        int a = t.a;
        int b = t.b;
        System.out.println(a+b);
    }
}
J.d. Patel
  • 11
  • 2
1

No as stated by Mikhail; constructors are not inherited.

You cannot inherit a constructor from superclass into your subclass. However when an object is instantiated with the "new" operator in java, that object inherit all constructors from it subclass to it superclass(parent) even including those in abstract class(since they are also super class).

3iL
  • 2,146
  • 2
  • 23
  • 47