Saturday, September 11, 2010

Java Generics - Part 2

A custom parametrized type:

Consider the following oversimplified DAO interfaces:


 

public interface StudentDAO

{

   Student getStudent( Long studentId );

}

 

class Student

{

        private Long id;

        private String name;

        // accessors and mutators

}


 

The above interface is specific for Student. But the same interfaces will hold good for other entities too, like Professor, Course etc... If the interfaces like the above are to be implemented, then there would be a Professor getProfessor( Long professorId ), Course getCourse( Long courseId). This is redundant, violates the DRY (Do not Repeat Yourself) principle. Since there is a getEntity() method is all the cases, the above interface can be written using generics as follows:

 


 

public interface DataAccessInterface<T> // 1 Parameterized type 2 T is formal type paramter

{

        T getEntity( Long EntityKey ); // 3 T can be used where ordinary types can be used

}


The above DAO interface will be used as follows:


 

        DataAccessInterface<Student> studentDAO; // 4 Student is actual type argument


 

Now, DataAccessInterface<T> is a parameterized type, T is the name of the formal type paramter. After T has been declared in the interface declaration, it can be used instead of normal types throughout the interface declaration.

When a reference to a parameterized type is declared (at 4 above), the actual type to be passed to the formal types is also specified. At this time, all occurrences of the formal type (T) will be replaced by the actual type (Student).

No comments: