I'm not sure what the purpose of override
keyword is, in scala. If I have
trait Shape { def foo(v: Int) } class Triangle extends Shape { override def foo(v: Int) {} }
it behaves (apparently at least) exactly the same as it does without override
.
This is the concept of Scala method overriding and we use the 'override' modifier to implement this. Let's see Scala String Method with Syntax and Method. Technically, Scala method overriding is when a member M of class C matches a non-private member M' of a class from which C inherits.
The purpose of Method Overriding is that if the derived class wants to give its own implementation it can give by overriding the method of the parent class. When we call this overridden method, it will execute the method of the child class, not the parent class.
If you don't use the annotation, the sub-class method will be treated as a new method in the subclass (rather than the overriding method). 2) It improves the code's readability.
@Override annotation is used when we override a method in sub class. Generally novice developers overlook this feature as it is not mandatory to use this annotation while overriding the method.
In the case you are implementing an abstract method as in your example, it is not strictly necessary to add the override
modifier.
However, in case you want to override
a concrete method from the superclass, the override
modifier is necessary. This is to avoid accidental overrides which could happen with mixing composition -- mixing-in traits during some refactoring could easily introduce a method definition that could be overridden by the method defined in the body of the class, hence the need for explicitly stating that a method is an override.
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