I have several Java classes that extend various implementations of the generic List interface. They just write down everything that is added to the list.
The following is a list of LoggingArrayList. As the name suggests, it extends ArrayList. The LoggingLinkedList class is identical, except that it extends LinkedList.
My main goal is not to duplicate all the common code so that I can use a different base class. I try to adhere to the principle of DRY (Do not Repeat Yourself) as much as possible.
First of all, please do not suggest a better way to log. This is not my real application at all. This is an easy way to demonstrate the problem I am facing.
I have two closely related questions. The first is the question in the title. How can I refer to the super method in a Java class that implements an interface but does not extend another class?
The LoggingArrayList class, as shown below, works great, but when I change the class declaration from ... extends ArrayList to ... implements List, the three super.method () references are no longer invoked, so my first question.
A good answer to my second question will almost make the first question moot. The second question is: is there a way to declare an abstract base class, or perhaps an interface that extends the list with the default implementation of the various add () methods, so that I can simply extend this abstract base class or implement this interface and specify only which list will be the basis for a particular class?
For example, I would like to do something like this:
interface LoggingList<T extends Object, L extends List<T>> extends L {
... then I could just implement a LoggingList once for each concrete implementation of List without duplicating all the common code. Specific classes might look something like this without the extra code needed inside their braces:
public class LoggingArrayList<T extends Object> implements LoggingList<T, ArrayList<T>> {} public class LoggingLinkedList<T extends Object> implements LoggingList<T, LinkedList<T>> {}
The problem is that the interface definition, as I suggested, is invalid (will not compile), and the super.method (s) links in the code below are not available unless I make LoggingList an abstract subclass of the interface, and then I return back where I am now.
Thanks in advance for any ideas on how to fulfill my dry goal.
Here is my whole LoggingArrayList class.
public abstract class LoggingArrayList<T extends Object> extends ArrayList<T> { protected void log(T e) { System.out.println(e == null ? "null" : e.toString()); } @Override public boolean add(T e) { log(e);