Advertisement
Online Test Banks
Score higher
See Online Test Banks
eLearning
Learning anything is easy
Browse Online Courses
Mobile Apps
Learning on the go
Explore Mobile Apps
Dummies Store
Shop for books and more
Start Shopping

Create a Generic Class in Java

A generic class in Java is a class that can operate on a specific type specified by the programmer at compile time. To accomplish that, the class definition uses type parameters that act as variables that represent types (such as int or String).

To create a generic class, you list the type parameter after the class name in angle brackets. The type parameter specifies a name that you can use throughout the class anywhere you’d otherwise use a type. For example, here’s a simplified version of the class declaration for the ArrayList class:

public class ArrayList<E>

I left out the extends and implements clauses to focus on the formal type parameter: <E>. The E parameter specifies the type of the elements that are stored in the list.

To create an instance of a generic class, you must provide the actual type that will be used in place of the type parameter, like this:

ArrayList<String> myArrayList;

Here the E parameter is String, so the element type for this instance of the ArrayList class is String.

Now look at the declaration for the add method for the ArrayList class:

public boolean add(E o)
{
   // body of method omitted (thank you) 
}

Where you normally expect to see a parameter type, you see the letter E. Thus, this method declaration specifies that the type for the o parameter is the type specified for the formal type parameter E. If E is String, the add method accepts only String objects. If you call the add method passing anything other than a String parameter, the compiler will generate an error message.

You can also use a type parameter as a return type. Here’s the declaration for the ArrayList class get method:

public E get(int index)
{
    // body of method omitted (you’re welcome)
}

Here, E is specified as the return type. That means that if E is String, this method returns String objects.

The key benefit of generics is that type-checking happens at compile time. Thus, after you specify the value of a formal type parameter, the compiler knows how to do the type-checking implied by the parameter. That’s how it knows not to let you add String objects to an Employee collection.

  • Add a Comment
  • Print
  • Share
blog comments powered by Disqus
Advertisement
Advertisement

Inside Dummies.com

Dummies.com Sweepstakes

Win an iPad Mini. Enter to win now!