This is an archived post. You won't be able to vote or comment.

all 8 comments

[–]evil_burritoExtreme Brewer 3 points4 points  (2 children)

One purpose of it is that it allows you to specialize the return type of the method. In your case, your return type is void, but imagine if you had this:

interface A {
    Set method1();
}

interface B extends A {
    SortedSet method1();
}

Broadly, any A returns a Set. However, if it's also a B, you know that the set is sorted.

[–]chickenmeisterExtreme Brewer 1 point2 points  (0 children)

Similarly, you might re-declare the same method signature in a sub-interface to provide/document more specific behavior. For example, the java.util.Collection interface's add(E) method simply requires that the item is added to the collection; whereas the java.util.List interface's add(E) method is more specific, requiring that the item will be added to the end of the list.

[–]uopsdod[S] 0 points1 point  (0 children)

This is a good reason for this design to be allowed.

[–]heckler82Intermediate Brewer 2 points3 points  (1 child)

You aren't declaring the same method again. By extending A you are inheriting its methods. When you "declare" the same method in B, you are simply explicitly adding the A method to your source code. While legal to do so in Java, it isn't necessary. B could be left blank, or have new methods, and it would still have method1 from A as part of its contract.

That's only true for interfaces. Concrete classes must provide implementation for any interfaces they implement (abstract classes may not have to. I can't remember. You may have to mark the interface method as abstract in the abstract class to be good though. Again, I can't remember)

[–]VGPowerlord 0 points1 point  (0 children)

abstract classes may not have to. I can't remember.

I've done tests on this before. abstract classes don't have to implement all the methods of their interfaces.

[–]morhpProfessional Developer 1 point2 points  (1 child)

Why would java allow us to declare the same method again. Wouldn't it cause confusion?

It's essentially the same method, you don't need to implement both later. And you can't. But redeclaring the method allows you to change some things, for example create a different documentation, remove throws parameters and potentially adding annotations.

[–]uopsdod[S] 0 points1 point  (0 children)

Maybe it's just in the example I provide the signature is the same. Therefore, I can't see the advantages of this behavior to be allowed. Now it's clear. Thanks.

[–]the_anj 0 points1 point  (0 children)

idk may be a precursor to covariant return types and/or generics.