Reputation: 15
When extending the ArrayList class you could also edit its methods, right?
I would like to extend from ArrayList and have the add() method return an Object instead of boolean (or void). So I could do this:
CustomObject o = objectList.add(new CustomObject("myObject"));
This would be the class:
public static class ObjectList extends ArrayList<CustomObject>{
public CustomObject add(CustomObject object){
super.add(object);
return object;
}
public CustomObject add(int index, CustomObject object){
super.add(index, object);
return object;
}
}
But this won't work because these methods would normally return boolean or void as been documented in the Java docs: http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html#add(E)
So could this be possible another way?
Thanks for your help.
Upvotes: 0
Views: 647
Reputation: 29276
There are some rules that should be considered while overriding a method in Java and your scenario lies in first point.
Return type of overriding method must be same as overridden method. Trying to change return type of method in child class will throw compile time error "return type is incompatible with parent class method".
A method can only be overridden in sub class, not in same class. If you try to create two methods with same signature in one class compiler will complain about it saying "duplicate method in type Class".
Overriding method cannot throw checked Exception which is higher in hierarchy, than checked Exception thrown by overridden method. For example if overridden method throws IOException or ClassNotfoundException, which are checked Exception, than overriding method can not throw java.lang.Exception because it comes higher in type hierarchy (it's super class of IOException and ClassNotFoundExcepiton).
Overriding method can not reduce access of overridden method. It means if overridden method is defined as public than overriding method can not be protected or package private. Similarly if original method is protected then overriding method cannot be package-private.
Overriding method can increase access of overridden method. This is opposite of earlier rule, according to this if overridden method is declared as protected than overriding method can be protected or public.
private, static and final method can not be overridden in Java. By the way, you can hide private and static method but trying to override final method will result in compile time error "Cannot override the final method from a class"
Upvotes: 0
Reputation: 34003
You need to choose a different method name, e.g. addAndReturn
.
The reason is that method overloading does not work in Java if a method only differs in the return type (cf. Overload with different return type in Java?).
PS: You should also consider handling the return value of the original add
method and maybe return null
if adding failed for some reason.
Upvotes: 3