You are on page 1of 12

Generics in Java

Generics
 Generics means parameterized types
 It enables you to create classes and methods in which the
type of data upon which they operate is specified as a
parameter.
 Generic Classes
 Generic Methods
Generic Class
 A class that is defined with a parameter for a type is
called a generic class or a parameterized class
 The type parameter is included in angular brackets after
the class name in the class definition heading.
 Any non-keyword identifier can be used for the type
parameter, but by convention, the parameter starts with
an uppercase letter.
 The type parameter can be used like other types used
in the definition of a class.
Generic Class with one Type Parameter
Generic Type with Array Variable

Part 1
Generic Type with Array Variable

Part 2
Generic Type with Array Variable

Part 3
Generics works only with Objects!!
 When declaring an instance of a generic type, the type
argument passed to the type parameter must be class
type.
 You cannot use a primitive type, such as int or char…
Sample<int> ob1=new Sample<int>();

Sample<float> ob2=new Sample<float>(); ERROR


Sample<byte> ob3=new Sample<byte>();
Creating a Generic Method
Syntax:
<type-param-list> ret-type methname(paramlist)
{}
Example:
<T> void printArray(T [ ] y)
{ }
– it can be called by any parameter
– behavior of the method will be according
to the parameter passed
Generic Method
Generic Method
Thank You

You might also like