You cannot override the add method with the same signature and return a different type. Since the add(T t) method is defined in the Collection interface as returning a boolean, all methods in the type hierarchy with the same signature must return a boolean.
You can however:
Change the Signature by adding more arguments:
public class MyList<T> extends ArrayList<T> {
public String add(T t, String success, String error){
if (add(t)) {
return success;
} else {
return error;
}
}
}
or
Change the Signature by using a different method name:
public class MyList<T> extends ArrayList<T> {
public String addItem(T t){
if (add(t)) {
return "success";
} else {
return "error";
}
}
}
or
Use a wrapper class that uses aggregation of an ArrayList to do the underlying operations. But you will have to implement all the methods get, add, size, etc
public static class MyArrayList<T> {
private List<T> list;
public MyArrayList() {
this.list = new ArrayList<T>();
}
public String add(T t) {
if (list.add(t)) {
return "success";
} else {
return "error";
}
}
public T get(int index) {
return list.get(index);
}
}
ArrayList. You can overload it, though; but you'd need another parameter to the method to disambiguate it fromboolean add(E). (Or you could give it a different name).addmethod.