1

Is there possible to add a new custom method to the well-known interface List in a way in Java? I tried to implement List interface to "public abstract class MyList", however, I would like to achieve it remaining the same name of the interface "List". For example, later implememnt in the following way:

List mylist = new ArrayList();
mylist.newmethod();
Darius Miliauskas
  • 3,391
  • 4
  • 35
  • 53
  • extend it `public interface YourList extends java.util.List` – jmj Jan 15 '15 at 03:00
  • Imagine if this was possible. You could write this method: `public static void doStuff(List l) {l.newmethod();}`. Then someone else could write `doStuff(new ArrayList())`. What happens? – user253751 Jan 15 '15 at 03:05
  • 1
    @immibis other languages (e.g. Objective C) support these types of extensions and avoid these problems. It can be very convenient. – sprinter Jan 15 '15 at 03:09

3 Answers3

6

No, Java does not support such a feature. Use composition.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
6

You could extend it to another interface

interface MyList<E> extends List<E> {
    //add new methods here
}
jmj
  • 237,923
  • 42
  • 401
  • 438
  • 2
    The nice thing about this solution is that you can extend `List` implementations, and have them implement this. So you can write something like `public class MyArrayList extends ArrayList implements MyList` and just write those methods in it that you've listed in `MyList`. – Dawood ibn Kareem Jan 15 '15 at 03:07
  • 1
    The disadvantage of this approach (as opposed to languages that allow extension) is that it doesn't then apply to all the classes that have already implemented List. – sprinter Jan 15 '15 at 03:10
  • Haha, bring on Java 8's "default implementations". @sprinter – Dawood ibn Kareem Jan 15 '15 at 03:13
1

Here's what you want to do. I wouldn't recommend it though, it can be confusing to have two List classes.

public abstract class List implements java.util.List {
    public void myMethod() {
        ...
    }
}
eduardohl
  • 1,176
  • 2
  • 10
  • 23