为什么构造函数不能是最终的、静态的或抽象的? [英] 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屋!