I’ve recently learned like 3 new languages and I’m starting to get them confused. I haven’t worked Java in doing anything particularly complex (outside of android) in a couple years. I’m having trouble remembering if this is possible:
I’m subclassing ArrayList mainly so I can keep the arraylist ordered. I’m trying to override the add(object) method but I want it to return an int instead of a boolean (the location of the object that was added). But I’m getting errors on the return type of my method.
Is what I want even possible in the language? Can you have a method in a subclass return something different than the superclass’ method?
Or am I trying to do something stupid? Is this breaking the is-a idea of inheritance? Should I just encapsulation an arraylist instead of extending it?
For reference, a portion of what I’m trying to do:
public class AuthorArray extends ArrayList \{
@Override
public int add(Author object) {
super.add(object);
Collections.sort(this, new SortByLastName());
return this.indexOf(object);
}
}
In general, no. The only exception is covariant return types, when an overridden method returns a subclass of the return type in the base class/interface method. This became possible with Java5, and is good practice. But your case does not fall into this category.
Yes. Users of
ArrayListexpect to get abooleanreturn value fromadd, and see the elements in the same order they added them, and you would break that expectation. Don’t do that.Yes. Then you can define your own interface, with whatever contract you prefer. But first, consider using a
TreeSetinstead.