Why are constructors not inherited in java?

后端 未结 12 1273
被撕碎了的回忆
被撕碎了的回忆 2020-11-27 14:24

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<

12条回答
  •  -上瘾入骨i
    2020-11-27 15:01

    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(); }
    }
    

提交回复
热议问题