When you want to add some extra information into a class, what way would you prefer: would you extend that class or make a wrapper around it?
In my particular scenario, I want to add some pagination information with a List
that I get from database. That pagination information will include:
int currentPage;
int totalResults;
int containedResultsIndex;
int totalcontainedResults;
and a couple of methods:
Boolean isNextPageAvailable();
Boolean isPrevPageAvailable();
Whats your opinion, extend or wrap?
A Wrapper class is a class whose object wraps or contains primitive data types. When we create an object to a wrapper class, it contains a field and in this field, we can store primitive data types. In other words, we can wrap a primitive value into a wrapper class object.
Definition and Usage The extends keyword extends a class (indicates that a class is inherited from another class). In Java, it is possible to inherit attributes and methods from one class to another. We group the "inheritance concept" into two categories: subclass (child) - the class that inherits from another class.
They are automatically synchronized as their state can not be altered by virtue of the definition of immutability. There are zero scopes of inconsistency as an object of the wrapper class can not be altered.
Extends: In Java, the extends keyword is used to indicate that the class which is being defined is derived from the base class using inheritance. So basically, extends keyword is used to extend the functionality of the parent class to the subclass. In Java, multiple inheritances are not allowed due to ambiguity.
It sounds like you're asking whether you should favor inheritance or composition in your situation. I would say that you are not creating a new implementation of List
and you don't really care how List
is implemented, so inheritance doesn't fit your problem. Instead, you're providing paging functionality. I would create a class that generically wraps up (encapsulates) the paging logic using List
or some other generic collection.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With