你把super()调用作为你的构造函数的开始吗? [英] Do you put a super() call a the beginning of your constructors?

查看:200
本文介绍了你把super()调用作为你的构造函数的开始吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是有关编码风格和建议做法的问题:

This is a question about coding style and recommended practices:

如问题不必要把super()在构造函数?,如果你写一个类的构造函数,应该使用默认(无arg )构造函数,您可以在构造函数开头调用 super()

As explained in the answers to the question unnecessary to put super() in constructor?, if you write a constructor for a class that is supposed to use the default (no-arg) constructor from the superclass, you may call super() at the beginning of your constructor:

public MyClass(int parm){
  super(); // leaving this out makes no difference
  // do stuff...
}

但您也可以省略通话;

but you can also omit the call; the compiler will in both cases act as if the super() call were there.

那么,你把这个调用放到你的构造函数中吗?

So then, do you put the call into your constructors or not?

一方面,可能会认为包含 super()会使事情更加明确。 OTOH,我总是不喜欢写冗余代码,所以个人我倾向于离开它;但我经常在别人的代码中看到它。

On the one hand, one might argue that including the super() makes things more explicit. OTOH, I always dislike writing redundant code, so personally I tend to leave it out; I do however regularly see it in code from others.

你的经验是什么?你有一个或另一种方法的问题吗?

What are your experiences? Did you have problems with one or the other approach? Do you have coding guidelines which prescribe one approach?

BTW:一个相关问题(仅供参考):

BTW: A related question (just for reference):

有没有理由在没有其他构造函数时显式地编写默认构造函数?

推荐答案

super()调用同样的原因,我不写不必要的转换:

I don't write the super() call for the same reason I don't write unnecessary casts:

代码,而不提供任何附加信息(无论是编译器还是给开发者阅读我的代码)。

It adds noise to the code without providing any additional information (neither to the compiler nor to the developer reading my code).

这篇关于你把super()调用作为你的构造函数的开始吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆