Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing a method of interface is overriding or not in java

I know this might be crazy but today one of my friend puzzled by asking when we implement an interface in java is it considered as method overriding. I told him it is not overriding as we are providing working(definition) of method first time when we implement any interface. To support multiple inheritance java provide interface but he was not convinced and was arguing. Please bring some light on to the topic.

like image 245
CodingRat Avatar asked Feb 26 '15 14:02

CodingRat


2 Answers

The term "overriding" applies when there is an existing implementation of the method . The correct term is "implementing" for interfaces and other abstract declarations.

The @Override tag is used for both cases - it is used when:

The method does override or implement a method declared in a supertype. --javadocs

And from Wikipedia:

Method overriding, in object oriented programming, is a language feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its superclasses or parent classes.

Note that interfaces can have default methods - redefining these methods overrides them:

When you extend an interface that contains a default method, you can ... redefine the default method, which overrides it.

Besides linking to "canonical" sources, I'm not sure what advice to offer on winning a semantic argument with your friend. Perhaps you could ask him what the distinction is between "implementing" and "overriding", and what word he would use instead of "overriding" for the concept of redefining an existing method.

like image 82
mk. Avatar answered Sep 18 '22 10:09

mk.


At first glance, interfaces just define API. Since there is no super method to override, the implementations is the first method.

But since Java 5, it's customary to add @Override annotations even for methods which come from interfaces. The main reason here is to catch problems which happen when people change an interface: Now you have a method which is "dangling" - there is no API which says that the method has to be there. The annotation causes an error if you remove a method from the interface, catching this so you can properly clean up all the code.

But that still doesn't mean the implementing method overrides anything.

Except that an interface is very much an abstract class with abstract methods in the byte code. And abstract methods do override.

My feeling is that you can argue both ways but the argument is moot unless you have a use case there the answer to the question actually has a real impact on the code. And here, it doesn't really matter since the compiler hides all the ugly details.

like image 23
Aaron Digulla Avatar answered Sep 19 '22 10:09

Aaron Digulla