I have mostly used generics to make type safe collections.What are the other uses of generics?
I've used it to write a very slim DAO-layer:
/*
superclass for all entites, a requirement is that they have the
same kind of primary key
*/
public abstract class Entity {
}
/*
superclass for all DAOs. contains all CRUD operations and anything else
can be generalized
*/
public abstract class DAO<T extends Entity> {
//assuming full control over the database, all entities have Integer pks.
public T find(Integer pk) {...}
public void save(T entity) {...}
public void remove(T entity) {...}
etc...
}
/*
Complete example of an ideal DAO, assuming that there are no special
operations specific for the Entity.
Note the absence of any implementation at all.
*/
public class SpecificDAO extends DAO<SpecificEntity> {}
To allow user-created, custom classes to be used with your code.
Say you release an SDK that enables some kind of special functionality. Generics will allow developers to utilise your functionality in many places, with almost any class.
The purpose of generics to reduce code repetition.
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