为什么在Java中不继承构造函数? [英] Why are constructors not inherited in java?
问题描述
我是Java编程语言的初学者,最近我研究了构造函数不能在Java中继承,有人可以解释为什么吗?
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?
我已经阅读了 C ++的此链接
推荐答案
简单来说,构造函数无法继承,因为在子类中,构造函数具有不同的名称(子类的名称).
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();
}
您只能执行以下操作:
B b = new B(); // and not new A()
方法是使用相同名称"继承的,可以使用.
Methods, instead, are inherited with "the same name" and can be used.
原因: 继承构造函数没有多大意义,因为类A的构造函数意味着创建一个A类型的对象,而类B的构造函数意味着创建一个B类的对象.
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.
尽管如此,您仍然可以在B的实现中使用 A中的构造函数:
You can still use constructors from A inside B's implementation though:
class B extends A{
B() { super(); }
}
这篇关于为什么在Java中不继承构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!