Reputation: 139
What does the override
do here? After deleting override
, I can still compile the program.
abstract class Animal {
def name: String
}
class Cat extends Pet {
override def name: String = "Cat"
}
Adapted from Tour of Scala: Upper Type Bounds: https://docs.scala-lang.org/tour/upper-type-bounds.html
Upvotes: 0
Views: 55
Reputation: 2638
You are right, this is a particular case where removing it does not affect the program. Why override
is allowed here is for various flexibility reasons:
Animal
- that would work without affecting the behavior of Cat
because you used the prophylactic
override
in Cat
to prevent that idea from affecting your extended class. So the subclass becomes just a little bit less tightly-coupled from your base class in this case.name
or renames it in the parent class (without knowing that method is being overridden). This would raise compile errors in all classes that overridden it, to he/she will know that this change should be thoroughly thought before being done, as it will affect the interface and the way clients interact with your code.name
for something else, say nme
- you'll see that if you used override
the compiler will warn you that nme
does not override anything in the base class. (Thanks compiler!)override
in subclasses acts as a marker so I know that this method is also defined in the base class, without having to manually check the base class, which usually resides in a different file.So it's more of a "best practice" thing rather than a necessity in this case, and everyone is free to use it as they see fit.
Upvotes: 1