1

I came across Collection interface, which declares add() method as follows:

boolean add(E e);

Then I came across Set interface, which extends Collection, which declares add() method with same above signature.

Since the signatures are same, I suppose Set is overriding method in Collection. The only difference I can notice is in comments. Collection says:

Ensures that this collection contains the specified element.

Set says:

Adds the specified element to this set if it is not already present.

So I feel, technically, we can omit declaration of add from Set and still the whole Java collections framework would have behaved without any issue, but its there simply because in Set, add() has different meaning than that in Collection. Q1. Is it so? Or anything else is achieved with overriding add() in Set?

Q2. Is this normal usage pattern across the framework? Does any other interface hierarchy follow the same?

Q3. How correct it is to override method from super interface in sub interface, just because it has different meaning in sub interface, even though it has same signature? (Is it that this is perfectly correct and as expected and I am unnecessarily finding it surprisingly weird because I am facing it for first time?)

MsA
  • 2,599
  • 3
  • 22
  • 47
  • 3
    Q1: Yes I believe it's simply to add the better documentation. Q2: yes check out the `List` interface, it also defines the add method with better documentation Q3: It is correct. You aren't defining any implementation so you aren't technically overriding, you are just defining better in the documentation on how the method should be implemented – RobOhRob Mar 17 '20 at 19:29
  • 3
    Think of it this way, if you were defining your own Set implementation and your own List implementation and all you had was the javadoc on the Collection... would you know exactly how it should behave? The Collection javadoc is more generic, the Set and List javadocs are more specific, because they describe a more specific implementation – RobOhRob Mar 17 '20 at 19:31
  • 1
    Related: https://stackoverflow.com/q/50695623/2711488 – Holger Mar 18 '20 at 13:59

0 Answers0