Java Basics
Commentary: Always write super()?
Issue. The first statement of every constructor is either a call to
another constructor in the same class, this(...)
, or a call
to the parent class constructor, super(...)
, whether your write
it explicitly or not!
Implicit super(). If you don't write either constructor call
explicitly, the compiler automatically inserts a call to the
parameterless superclass constructor, super()
.
Should there be invisible code? Some programmers / instructors feel that unseen code generation reduces the comprehensibility of programs, and creates areas where students might not understand what's going wrong when they get error messages, have performance issues, or run out of memory.
Typical error. The automatically inserted super constructor call is parameterless, which is OK if the superclass has a parameterless constructor. But if it doesn't, the automatically generated super() call fails to compile, which can be confusing when the programmer gets an error message for a statement they can't even see!
Other automatically generated code. There are lots of places unseen code is generated. Of course all statements in Java hide the actual machine code that's generated, but most programmers accept that, altho some instructors feel that the best way to teach programming is to teach machine/assembly language.
Recent versions of Java have added features which automatically generate code. For example,
- Auotboxing hides object creation in converting primitive types to their wrapper types.
- Foreach implicitly uses an iterator.
- Generic data structures hide casts.
- Variable parameter lists hide array creation.
Your choice. As a practical matter, many of these allow writing simpler programs, which is why I use all of them. That they may also cause problems for the unaware may be a good reason to avoid them during the learning stage.
When I first learned about implicit super()
generation, I went
through a phase of explicitly writing it, and simplarly with autoboxing.
But eventually I became comfortable with these, and I suspect this happens to
a lot of programmers.