Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java extend or wrap a class to add extra functionality

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?

like image 291
craftsman Avatar asked Jan 27 '10 21:01

craftsman


People also ask

What does it mean to wrap a class in Java?

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.

What happens when you extend a class in Java?

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.

Can we extend wrapper class in Java?

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.

Why do we extend classes in Java?

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.


1 Answers

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.

like image 69
Jonathon Faust Avatar answered Oct 19 '22 15:10

Jonathon Faust