Should I extend ArrayList (is-a) or include it as a member (has-a)?

I am making a simple program that supports a list of numbers, and I want the list to also have a name. Which one works best: do I include my ArrayList list class or include an ArrayList element? In both cases, there would of course be a "name", a member of String.

The first approach means that I only need to implement getter and setter for the name, but I think this binds my class too much to a specific implementation? For example, if I wanted to use Vector, then I would have to change the code everywhere.

The second approach will simplify the implementation change, but, of course, now it is becoming quite annoying, since I have to implement a wrapper package.

I read SO posts regarding inheritance and composition, and since my list is a type of ArrayList, I am leaning towards the first approach. However, are there any differences in the discussion because I am extending the Collection class and extending the general class? Or am I thinking too much about this?

+5
source share
6 answers

Nothing is better, his compromise, as you mentioned.

If you are performing aggregation (has-a), you need to wrap all the functions of the member that you are going to use (for example, implement the functions that call them)

If you are doing inheritance, a lot of functions are added to the new class that may be unnecessary, and you also need to implement abstract functions.

++, ,

+2

Guava ForwardingList. :

public class NamedList<E> extends ForwardingList<E> implements RandomAccess {
  // could also let the user provide the delegate list
  private final List<E> delegate = Lists.newArrayList();
  private String name;

  @Override protected List<E> delegate() {
    return delegate;
  }

  // constructors, getter, setter
}

, , , , " Java- 16" ( 2- ) " ". , (, add addAll).

Guava Forwarding* .

+3

, . , , , . ArrayList, , . , , , . ( ) , , , .

+2

- HAS-A. .

+1

@AbiusX , . . , , :

public class MyClass implements List
{
    private String name;
    private List myList = new ArrayList();

    public MyClass(String name)
    {
        this.name = name;
    }

    public String getName()
    {
        return name;
    }

    public void setName()
    {
        return name;
    }

    @Override
    public void add(int index, Object element)
    {
        myList.add(index,element);
    }

    @Override
    public boolean add(Object o)
    {
        myList.add(o);
    }

    @Override
    public boolean addAll(Collection c)
    {
        myList.addAll(c);
    }

    //so on for rest of methods in List interface
}

Generics, .

+1

ArrayList , . , Collections, , , , .

0

All Articles