“super”关键字在使用Eclipse中基于字段生成的构造函数中的作用是什么?

huangapple go评论71阅读模式
英文:

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&#39;t done in `SuperExample`, then the call to `super()` in `SuperExample.SuperExample()` will make sure that processing happens.

Now, you&#39;re right in that the `super()` call isn&#39;t really necessary in this case, because `Object` doesn&#39;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&#39;t do anything important in its constructor, because maybe sometime in the future it will.

It&#39;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&#39;t hurt anything, so why waste the effort optimizing it? That&#39;s the main reason.

</details>



huangapple
  • 本文由 发表于 2020年10月19日 11:27:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/64420759.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定