Why are constructors not inherited in java?

后端 未结 12 1276
被撕碎了的回忆
被撕碎了的回忆 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条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-27 15:17

    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

提交回复
热议问题