What are the benefits of using composition over inheritance when we need to add behavior to List <>?

What are the advantages / disadvantages of option 2 compared to 1 in this example?

Option 1 (Inheritance):

public class SalesList : List<Sales>
{
    //methods that add extra behavior List<Sales>
}

Option 2 (composition):

public class SalesList 
{
    private List<Sales> _list;
    //methods that add extra behavior to List<Sales>
}
+5
source share
5 answers

Option 1
 - Advantages - all the benefits of inheritance and reuse
 - Disadvantages - the code now signals to consumers that it is hidden from the List. If this needs to be changed later, all affected consumers will be affected.

2
 - - . , (, , ), .
 - - SalesList / _list. , . , , , ...

, .

.

+1

2 - . , , .

, . , List, : add/addAll/contains/retainAll. .

, " , ", Bumper-Sticker API Design. API , . , .

+2

Composition , () , , Inheritance , ( # , "", Java "final" ).

# 3 , .

+2

Inheritance , * * , * sub * set, ,

+2

. , , .

, , .

0

All Articles