为什么构造函数不能在java中继承? [英] Why constructors can not be inherited in java?
问题描述
我是java编程语言的初学者,最近我研究过构造函数不能在java中继承,任何人都可以解释为什么? b
$ b
我已阅读 C ++的链接
简单来说,构造函数不能被继承,因为在子类中有不同的名称(子类的名称)。
class A {
A );
}
B类扩展A {
B();
}
您只能执行:
B b = new B(); //而不是新的A()
可以使用。
由于原因:
继承一个构造函数没有太大意义,因为A类的构造函数意味着创建一个类型的对象A,B类的构造函数意味着创建B类的对象。
你仍然可以使用
class B extends A {
B(){super(); }
}
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++
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(); }
}
这篇关于为什么构造函数不能在java中继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!