here, Orca class extends SeaCreture(abstract class with an abstract method) & implements CanSwim(has one method). The solution shows one method that is being overridden (@Override - CanSwim).
It looks like it's the abstract method that is getting implemented, which it should. However, shouldn't the void swim() be implemented as Orca class implements CanSwim interface? why is this method being ignored?
interface or abstract class?
Under discussion
Comments (5)
- Popular
- New
- Old
You must be signed in to leave a comment
John
11 June 2021, 02:20
As you can see the void swim is already implemented in its abstract class and is not an abstract method, so the compiler wont force you to override the same method as it has already an implementation ;)
+1
ImDevin
11 June 2021, 04:13
why is it implemented in SeaCreature class? SeaCreature is not the class that implements CanSwim! It's Orca and Whale.
0
Thomas
11 June 2021, 06:00
It's to show you that it is possible. CanSwim asks the first concrete class that implements this interface (here eg. Orca) to implement the method as well. Orca extends SeaCreature and hence inherits all the methods that class has. And there you have the already implemented canSwim method. It is as if Orca has that methods itself. So the interfaces requirement is fullfilled. If you however make the canSwim method in the abstract class protected then that won't work. The interface methods are all public and all overridden methods need to be public as well.
You just can't use the annotation @Override here as at the time you could write it, it doesn't override any method.
+1
ImDevin
11 June 2021, 13:17
thx for the reply Thomas. So, you're saying, since Orca inherits all SeaCreature's methods, it's ok to implement it in SeaCreature. So in theory, if Orca implements multiple interfaces and altogether has 10 methods, it could all be in SeaCreature, not in Orca? You'd probably wouldn't do that, but I just didn't know it could work that way.
0
Thomas
11 June 2021, 16:58
That's exactly how it works. If you implement an interface then the requirement is, the declared method has to be publically accessible inside of the implementing class. It doesn't matter if these methods are inherited.
0