Is it good practice to use the override
keyword when implementing abstract methods defined in traits?
trait Tooth { def ache(): Unit } class Molar extends Tooth { override def ache(): Unit = {} }
In the above example, I understand that the override keyword is optional; but is it advisable? On which side of the terseness vs. safety trade-off should I fall?
A subclass must override all abstract methods of an abstract class. However, if the subclass is declared abstract, it's not mandatory to override abstract methods.
Overriding Abstract Classes in Java In Java, it is compulsory to override abstract methods of the parent class in its child class because the derived class extends the abstract methods of the base class. If we do not override the abstract methods in the subclasses then there will be a compilation error.
Abstract methods don't have any implementation and require non-abstract derived classes to implement them. Of course they are allowed only in abstract classes. Override allows a method to override a virtual or abstract method from its base class.
When the derived class inherits the abstract method from the abstract class, it must override the abstract method. This requirment is enforced at compile time and is also called dynamic polymorphism.
override
does one thing for you there: when removing Tooth.ache
but not its implementations later on, you will get compiler errors. In particular, this forces implementations of Tooth
(written by yourself or others) to be "close" to Tooth
in a certain sense, namely that deprecated methods vanish (or are at least reconsidered).
This may or may not be desired.
Personally, when I see
override def whatever()
the first thing I think is, "I wonder how this was supposed to behave before?"
Since this is an unhelpful thought if it was an abstract method, I find it both more terse and more safe to leave it off.
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