英文:
What is the purpose of the super keyword in the Constructor generated using fields in Eclipse?
问题
就像下面的例子一样。我知道在这种情况下可以删除super
关键字。但是我不明白为什么 Eclipse 总是默认生成这个关键字。除非 SuperExample
类继承另一个类,否则这个关键字应该没有任何意义。
public class SuperExample {
private int x;
public SuperExample(int x) {
super();
this.x = x;
}
}
英文:
Like the example below. I know that the super keyword can be deleted in this case. But I don't get why Eclipse always generates this keyword by default. This keyword should mean nothing unless the SuperExample class extends another class?
public class SuperExample {
private int x;
public SuperExample(int x) {
super();
this.x = x;
}
}
</details>
# 答案1
**得分**: 3
每个类默认都会继承 `java.lang.Object`,即使没有明确指定。如果在 `Object` 中有需要执行的构造操作而在 `SuperExample` 中没有执行,那么 `SuperExample.SuperExample()` 中的 `super()` 调用将确保进行该处理。
现在,你说得对,在这种情况下 `super()` 调用实际上并不是必要的,因为在其自己的构造函数中,`Object` 实际上并没有做任何特别的事情。但是你的集成开发环境(IDE)无论如何都会插入对 `super()` 的调用,因为,嗯,为什么不呢?即使超类的构造函数中没有执行重要操作,包含对 `super()` 的调用也是一种良好的实践,因为也许将来会有需要。
对于 Eclipse 来说,检查你的类是否继承了除 `Object` 之外的其他类,然后再自动生成构造函数中的 `super()` 调用,会增加更多的工作量。而且这样做并不会有什么坏处,那么为什么要浪费精力进行优化呢?这就是主要的原因。
<details>
<summary>英文:</summary>
Every class extends `java.lang.Object` by default, even if not specified. If there is construction to be done in `Object` that isn't done in `SuperExample`, then the call to `super()` in `SuperExample.SuperExample()` will make sure that processing happens.
Now, you're right in that the `super()` call isn't really necessary in this case, because `Object` doesn't actually do anything in particular in its own constructor. But your IDE will insert the call to `super()` anyway, because, well, why not? Including a call to `super()` is good practice even if the superclass doesn't do anything important in its constructor, because maybe sometime in the future it will.
It'd be more effort for Eclipse to check that your class extends something other than `Object` before auto-generating the `super()` call in the constructor. And doing so doesn't hurt anything, so why waste the effort optimizing it? That's the main reason.
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论