为什么构造函数不能是最终的,静态的或抽象的? [英] Why can't constructors be final, static, or abstract?
问题描述
为什么Java中的构造函数不能是最终的,静态的或抽象的?
Why can't constructors be final, static, or abstract in Java?
例如,您能向我解释为什么这无效吗?
For instance, can you explain to me why this is not valid?
public class K {
abstract public K() {
// ...
}
}
推荐答案
将方法设置为final
时,它的意思是:我不希望任何类重写它." 但根据Java语言规范:
When you set a method as final
it means: "I don't want any class override it." But according to the Java Language Specification:
JLS 8.8 -构造函数声明不是成员.它们从不继承,因此不受隐藏或覆盖."
JLS 8.8 - "Constructor declarations are not members. They are never inherited and therefore are not subject to hiding or overriding."
将方法设置为abstract
时,它表示:此方法没有主体,应在子类中实现." 但是,当使用new
关键字,因此它不会缺少正文.
When you set a method as abstract
it means: "This method doesn't have a body and it should be implemented in a child class." But the constructor is called implicitly when the new
keyword is used so it can't lack a body.
将方法设置为static
时表示:该方法属于类,而不是特定对象." 但是隐式调用了构造函数以初始化对象,因此存在拥有静态构造函数毫无用处.
When you set a method as static
it means: "This method belongs to the class, not a particular object." But the constructor is implicitly called to initialize an object, so there is no purpose in having a static constructor.
这篇关于为什么构造函数不能是最终的,静态的或抽象的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!