Generic Declarations in Java

Let us see the declaration of java.util.List interface.
Screen Shot 2018-12-20 at 10.18.12 AM

 

In the above declaration, “E”  is a placeholder for the type you pass in. The List interface is behaving as a generic “template” and when you write your code, you change it from a generic List to a List or List, and so on.

The E, by the way, is only a convention. Any valid Java identifier would work here, but E stands for “Element,” and it’s used when the template is a collection. The other main convention is T (stands for “type”), used for, well, things that are NOT collections.

Now that you’ve seen the interface declaration for List, what do you think the add() method looks like?
boolean add(E o)
In other words, whatever E is when you declare the List, that’s what you can add to it.

So imagine this code:

Screen Shot 2018-12-20 at 10.26.03 AM

The add() method of List must obviously behave like this:
boolean add(Animal a)

Defining Own Generic Class

Let us look into the below Generic Calculator Class that takes a Type “T”.

The add method takes two parameters of T type and returns the result of T type.

Screen Shot 2018-12-20 at 11.03.52 AM

Creating Generic method

The class itself doesn’t need to be generic; basically we may create a method that we can pass a type to and that can use that type to construct a type safe collection. Using a generic method, we can declare the method without a specific type and then get the type information based on the type of the object passed to the method.

Let us look into the below example.

Screen Shot 2018-12-20 at 11.17.13 AM

Leave a Reply

Your email address will not be published. Required fields are marked *