Reputation: 8244
In Scala, what's the difference between :
abstract class Car { def drive(distance: Integer) : Unit }
class BMW extends Car { def drive(distance: Integer) = println("I'm driving") }
and :
abstract class Car { def drive(distance: Integer) : Unit }
class BMW extends Car { override def drive(distance: Integer) = println("I'm driving") }
Specifically, what's the exact effect of the override
keyword?
Upvotes: 2
Views: 2372
Reputation: 28511
In your case none, because you are not providing a concrete implementation of the drive
method in abstract class Car
.
When defined like this:
def drive(distance: Integer) : Unit
The methods behave like Java interfaces. Specifically, any concrete implementers of the abstract class must define implementation for those methods.
You will even get an error otherwise. Something like: class BMW must be abstract
. The override
keyword is useless in your case, but if the method did have implementation:
class BMW extends Car {def drive(distance: Integer) = println("blabla"); }
Now this will require overriding in extending classes:
class BMWX5 extends BMW { def drive(distance: Integer) = println("x5"); } // won't work
class BMWX5 extends BMW { override def drive(distance: Integer) = println("x5"); }// will compile
Upvotes: 5
Reputation: 38045
override
is useful in case when you can create a new method instead of overriding existing method without knowing:
abstract class Car { def drive(distance: Integer) : Unit }
without override
:
abstract class BMW extends Car { def drive(distance: Int) = println("I'm driving") }
with override
:
scala> abstract class BMW extends Car { override def drive(distance: Int) = println("I'm driving") }
<console>:8: error: method drive overrides nothing.
Note: the super classes of class BMW contain the following, non final members named drive:
def drive(distance: Integer): Unit
abstract class BMW extends Car { override def drive(distance: Int) = println("I'm driving") }
^
In case of abstract
method override
keyword is not so useful, but it could be a good practice to override
even abstract methods just in case. It depends on conventions in project.
override
keyword for abstract methods makes it clear to readers that this method is defined in parent class/trait without looking to the parent class declaration.
Upvotes: 4