Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using the override keyword on implementations of abstract methods

Tags:

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?

like image 251
David Avatar asked Apr 13 '11 00:04

David


People also ask

Can you override an abstract method?

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.

Do you have to override abstract class 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.

What is abstract overriding?

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.

Is it mandatory to override abstract method in derived class C#?

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.


2 Answers

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.

like image 184
Raphael Avatar answered Sep 18 '22 09:09

Raphael


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.

like image 33
Rex Kerr Avatar answered Sep 17 '22 09:09

Rex Kerr