We’ve got the basics of OOP in Scala under our belt, but there’s plenty more to learn.
Classes and traits can declare abstract members: fields, methods, and types. These members must be defined by a derived class or trait before an instance can be created. Most object-oriented languages support abstract methods, and some also support abstract fields and types.
When overriding a concrete member, Scala requires the
override keyword. It is optional when a subtype
defines (“overrides”) an abstract member. Conversely, don’t use
override unless you are actually overriding a
override keyword has several benefits:
It catches misspelled members that were intended to be overrides. The compiler will throw an error that the member doesn’t override anything.
It catches a potentially subtle bug that can occur if a new
member is added to a base class where the member’s name collides with
an older derived class member that is unknown to the base class
developer. That is, the derived-class member was never intended to
override a base-class member. Because the derived class member won’t
override keyword, the compiler will throw
an error when the new base-class member is introduced.
Having to add the keyword reminds you to consider what members should or should not be overridden.
Java has an optional
@Override annotation for methods. It helps catch errors of the first type (misspellings), ...