Generics in Java

Introduction

Generics is a new feature introduced by JDK 1.5. Generics is basically used for type safe collections. Generics is the facility of defining classes having a variable type member, in other words in Generic classes the type of a member is specified at the time of object creation. With the help of this feature we are able to use multiple implementations of a class having members of various types.

Generic is "Type Safe"

To explain this concept of Type Safety in Generics we will consider the following example and see the corresponding output. Generics are added to provide compile time type safety in the code and to reduce risks due to ClassCastException during runtime. Here in the following example a String is type cast to the ArrayList, and if any type other than a string is assigned to it then let us see how the compiler reacts.

s1.jpg

The output of the code above will give the following error:

fig4.1.jpg

When we remove the statement "myList.add(10);", then the code runs successfully. The screenshots are as follows.

s.jpg

The output of the code above is:

fif4.2.jpg

So, from the preceding illustration now it's clear that a Generic is type safe.

Sensible is permitted and non-sensible is not permitted in a Generic class

The statements that are sensible that makes sense according to Java coding, is allowed in a Generic class. But the statements that are not sensible as per the Java coding is not permitted. It is illustrated below with an example.

s3.jpg

The output of the code above will be a compiler error, the screenshot is shown below:

fig4.3.jpg

The code above contains a non-sensible statement so there is a compiler error. When we remove this statement the following output is obtained.

s4.jpg

Output:

fig4.4.jpg

But in a non-Generic class, non-sensible is allowed but sometimes sensible statements are not permitted. The following example demonstrates this. Here the last statement does not make any sense but is permitted and the sensible statement "String s=strobj.getValue()" that is completely true according to Java, gives a compiler error.

s5.jpg

The output of the code above will produce a compiler error, the screenshot is:

fig4.5.jpg

After removing the errors, the following result is obtained.

s6.jpg

Output

fig4.6.jpg

Advantages of Generics:

  • Provides type safety
  • Eliminates type casting
  • Eliminates ClassCastException

Up Next
    Ebook Download
    View all
    Learn
    View all