Should we @Override an interface's method implementation?

Should a method that implements an interface method be annotated with @Override?

The javadoc of the Override annotation says:

Indicates that a method declaration is intended to override a method declaration in a superclass. If a method is annotated with this annotation type but does not override a superclass method, compilers are required to generate an error message.

I don't think that an interface is technically a superclass. Or is it?

Question Elaboration


Asked by: Walter337 | Posted: 21-01-2022






Answer 1

You should use @Override whenever possible. It prevents simple mistakes from being made. Example:

class C {
    @Override
    public boolean equals(SomeClass obj){
        // code ...
    }
}

This doesn't compile because it doesn't properly override public boolean equals(Object obj).

The same will go for methods that implement an interface (1.6 and above only) or override a Super class's method.

Answered by: Lyndon802 | Posted: 22-02-2022



Answer 2

I believe that javac behaviour has changed - with 1.5 it prohibited the annotation, with 1.6 it doesn't. The annotation provides an extra compile-time check, so if you're using 1.6 I'd go for it.

Answered by: Cherry270 | Posted: 22-02-2022



Answer 3

You should always annotate methods with @Override if it's available.

In JDK 5 this means overriding methods of superclasses, in JDK 6, and 7 it means overriding methods of superclasses, and implementing methods of interfaces. The reason, as mentioned previously, is it allows the compiler to catch errors where you think you are overriding (or implementing) a method, but are actually defining a new method (different signature).

The equals(Object) vs. equals(YourObject) example is a standard case in point, but the same argument can be made for interface implementations.

I'd imagine the reason it's not mandatory to annotate implementing methods of interfaces is that JDK 5 flagged this as a compile error. If JDK 6 made this annotation mandatory, it would break backwards compatibility.

I am not an Eclipse user, but in other IDEs (IntelliJ), the @Override annotation is only added when implementing interface methods if the project is set as a JDK 6+ project. I would imagine that Eclipse is similar.

However, I would have preferred to see a different annotation for this usage, maybe an @Implements annotation.

Answered by: Ada447 | Posted: 22-02-2022



Answer 4

I would use it at every opportunity. See When do you use Java's @Override annotation and why?

Answered by: Stuart366 | Posted: 22-02-2022



Answer 5

JDK 5.0 does not allow you to use @Override annotation if you are implementing method declared in interface (its compilation error), but JDK 6.0 allows it. So may be you can configure your project preference according to your requirement.

Answered by: Kelsey853 | Posted: 22-02-2022



Answer 6

If a concrete class is not overriding an abstract method, using @Override for implementation is an open matter since the compiler will invariably warn you of any unimplemented methods. In these cases, an argument can be made that it detracts from readability -- it is more things to read on your code and, to a lesser degree, it is called @Override and not @Implement.

Answered by: Maya625 | Posted: 22-02-2022



Answer 7

By reading the javadoc in java8, you can find the following at the declaration of interface Override:

If a method is annotated with this annotation type compilers are required to generate an error message unless at least one of the following conditions hold:

  • The method does override or implement a method declared in a supertype.
  • The method has a signature that is override-equivalent to that of any public method declared in {@linkplain Object}.

So, at least in java8, you should use @Override on an implementation of an interface method.

Answered by: Tara970 | Posted: 22-02-2022



Answer 8

Overriding your own methods inherited from your own classes will typically not break on refactorings using an ide. But if you override a method inherited from a library it is recommended to use it. If you dont, you will often get no error on a later library change, but a well hidden bug.

Answered by: Sam546 | Posted: 22-02-2022



Answer 9

It's not a problem with JDK. In Eclipse Helios, it allows the @Override annotation for implemented interface methods, whichever JDK 5 or 6. As for Eclipse Galileo, the @Override annotation is not allowed, whichever JDK 5 or 6.

Answered by: Walter750 | Posted: 22-02-2022



Answer 10

If the class that is implementing the interface is an abstract class, @Override is useful to ensure that the implementation is for an interface method; without the @Override an abstract class would just compile fine even if the implementation method signature does not match the method declared in the interface; the mismatched interface method would remain as unimplemented. The Java doc cited by @Zhao

The method does override or implement a method declared in a supertype

is clearly referring to an abstract super class; an interface can not be called the supertype. So, @Override is redundant and not sensible for interface method implementations in concrete classes.

Answered by: Alford989 | Posted: 22-02-2022



Answer 11

For me, often times this is the only reason some code requires Java 6 to compile. Not sure if it's worth it.

Answered by: Edgar523 | Posted: 22-02-2022



Answer 12

The problem with including the @Override is that it makes you think that you forgot to call the super.theOverridenMethod() method, which is very confusing. This should be crystal-clear. Perhaps Java should offer an @Interface to be used here. Oh well, yet another half-assed Java peculiarity...

Answered by: Sawyer965 | Posted: 22-02-2022



Answer 13

In java 6 and later versions, you can use @Override for a method implementing an interface.

But, I donot think it make sense: override means you hava a method in the super class, and you are implementing it in the sub class.

If you are implementing an interface, I think we should use @Implement or something else, but not the @Override.

Answered by: Sydney294 | Posted: 22-02-2022



Answer 14

Eclipse itself will add the @Override annotation when you tell it to "generate unimplemented methods" during creation of a class that implements an interface.

Answered by: Daniel275 | Posted: 22-02-2022



Answer 15

This might be too late answer. But I hope this example would help someone to understand why @override is so important (for a scenario like this)

public interface Restaurant(){
    public boolean getBill();
    public BigDecimal payAmount();
}

public interface Food() extends Restaurant{
    public boolean haveSomeFood();
    public boolean drinkWater();
}

public class Hungry() implements Food{
    public boolean haveSomeFood(){}
    public boolean drinkWater(){}
    public boolean getBill(){}
    public BigDecimal payAmount(){}
}

In the above example, If I am Hungry, I can have Food from a Restaurant. But if I took out the implementation of Restaurant, I do not have to get a bill and no need to pay the amount!!!!

How?

  • The interface Food has the keyword extends Restaurant - which means the class Hungry is also implemented from the interface Restaurant.
  • The methods actually overriden from the interface does not have the keyword @override
  • So, if I remove the keyword extends Restaurant (or say if I remove the interface Restaurant, it will not show any error.

If there was @override, whenever I am trying to remove the Restaurant interface it will show compilation error.

Note: When you implement an interface, you might not know whether that interface is extended to another interface or can be extended or the inheritance may be removed. So it is always better to use @override keyword

Answered by: Lenny846 | Posted: 22-02-2022



Similar questions

java - What Exception is thrown when an implementation breaks its interface's contract?

Through a good amount of debugging (I do not wish to repeat) I've found a circumstance that can only be arrived at if one of my objects was given a comparator that breaks its interface's contract (namely a Comparator for which compare(a, a) returns a non-zero value). What kind of exception should I throw? I thought I could take inspiration from TreeMap, which takes a comparator, but it simply a...


java - AspectJ - pointcut for methods of interface's implementation

I have several implementations of SomeInterface. The question is what is the pointcut for the method executeSomething in all implementation of SomeInterface. public class SomeImplementation implements SomeInterface { public String executeSomething(String parameter) { // Do something } } public class AnotherImplementation implements SomeInterface { public String executeSomething(Strin...


java - JMockit unable to capture argument on interface's implementation

I am new to JMockit and I couldn't get a working solution to my current issue from the previous posts here. I am trying to mock an interface method and verify that it is called with an expected argument. The captureWith() in the Verifications() block is failing to capture the object. However, when I use NonStrictExpectations() instead of Expectations() it is capturing the argument. I want to use Expectation...


java - How to find usages of ONE implementation of an interface's method

I have a project with hundreds of implementations of an interface. I'd like to find the usages of a method in just ONE implementation of that interface. Intellij (and Eclipse) both show me all usages of that method in all of the implementations - hundreds of them. I highlight the method in one implementation of the interface, right-click and select "find usages", and it shows me all usages of that method in all imp...


java - Default Handler implementation breaking on nbsp

I have an implementation of default handler. When it gets to a   in the character data it stops parsing. Is there any reason that it is doing this? Are there additional properties that I need to set in order for it to deal with &nbsp?


data structures - KDTree Implementation in Java

I'm looking for a KDTree implementation in Java. I've done a google search and the results seem pretty haphazard. There are actually lots of results, but they're mostly just little one-off implementations, and I'd rather find something with a little more "production value". Something like apache collections or the excellent C5 collection library for .NET. Something where I can see the public bug tracker and check to se...


java - is there a merged iterator implementation?

Is there an Iterator implementation that merges multiple iterators? class MergedIterator<T> implements Iterator<T> { MergedIterator(Iterator<T>... iters) .... } And the next method should move on to iters[1] when !iters[0].hasNext() etc


java - Is there a free (LGPL, BSD, etc) implementation of XML editor swing component

I need a JComponent thad enables editing xml documents so I can embed it in my application. It doesnt need to bee fancy. Plain text editing and highlighting would bee enough. Thank in advance


jsp - Is there an openID implementation in Java?


Java: Specifying generics on Type AND Implementation

Most references I've seen, and my IDE's code completion all have my specifying a Generic type on both a variables type and its implementation eg. List<String> string = new ArrayList<String>(); Recently I've started skipping the generic type on the implementation eg. List<String> strings = new ArrayList(); assuming that the compiler is onl...


java - Interface implementation through different JVMs

Lets say you have interface definition. That interface can be Operation. Then you have two applications running in different JVMs and communicating somehow remotely by exchanging Operation instances. Lets call them application A and application B. If application A implements Operation with the class that is not available in the classpath...


java - How to simplify a null-safe compareTo() implementation?

I'm implementing compareTo() method for a simple class such as this (to be able to use Collections.sort() and other goodies offered by the Java platform): public class Metadata implements Comparable<Metadata> { private String name; private String value; // Imagine basic constructor and accessors here // Irrelevant parts omitted } I want the natu...


MPI implementation for Java

Is there a current Java MPI implementation. I have programmed in MPI a bit, and I enjoy programming in Java. I have seen this implementation in Java, but it seems dated. Is there a more up to date Java implementation that is being kept up?


How can I translate printf("%c",M); from C to Java for my DES implementation?

I'm a German student and for computer classes I need to implement the DES-encryption in Java (by myself, not by using the Java-API) and explain it in detail. I didn't find any Java-code-examples using google, however I did find an easy implementation in C. (I do not know C, I know a little C++, but not that well, pointer...






Still can't find your answer? Check out these amazing Java communities for help...



Java Reddit Community | Java Help Reddit Community | Dev.to Java Community | Java Discord | Java Programmers (Facebook) | Java developers (Facebook)



top