Just removed the following code from a colleague's code:
public ClassName() {
super();
}
I just want to make sure I did the right thing. Why would someone intentionally write this? This is exactly what the compiler inserts by default isn't it?
Edit:
To clarify: that's the only constructor.
Also, this is not a trick question. The guy who wrote this is more senior than me, so I want to make sure I covered all possibilities before I talk to him about this.
If you have a non-default constructor in your code then compiler will not provide a default no parameter constructor. So if someone tries to create an object using new YourClass()
. This will cause a compilation error.
Therefore you need to make sure that there are no references in your code for that class default constructor in case if there are other constructors present.
The other answers are already good, but for posterity/fun, it's worth noting:
super()
call is always superfluousTo demonstrate, here are four classes:
public class Base {}
public class SubA extends Base {
// nothing
}
public class SubB extends Base {
public SubB() {
// nothing in ctor
}
}
public class SubC extends Base {
public SubC() {
super();
}
}
If you run javap -c
on each of the three subclasses, you'll see their generated bytecode is exactly the same (other than their class names, of course):
$ javap -c SubA SubB SubC
Compiled from "SubA.java"
public class SubA extends Base{
public SubA();
Code:
0: aload_0
1: invokespecial #1; //Method Base."<init>":()V
4: return
}
Compiled from "SubB.java"
public class SubB extends Base{
public SubB();
Code:
0: aload_0
1: invokespecial #1; //Method Base."<init>":()V
4: return
}
Compiled from "SubC.java"
public class SubC extends Base{
public SubC();
Code:
0: aload_0
1: invokespecial #1; //Method Base."<init>":()V
4: return
}
There is no good technical reason for this. Not everybody bothers to learn the rules about default constructors and many people just like to do things the way they always have. I don't like having useless stuff like this in the code base. However, since it doesn't do any damage, removing it isn't a high priority either, so I'd leave it alone unless wholesale rework is needed.
A key to keeping your sanity in a workplace where you have to share code with others is to accept that your cow-orkers will do things differently from you. Consider limiting changes to others' code to things that matter. And don't be surprised if questioning them about their mindless habits or obsessive-compulsive idiosyncracies is not productive.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With