Generic programming in java

anshu_atri 120 views 13 slides Sep 17, 2020
Slide 1
Slide 1 of 13
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13

About This Presentation

www.acem.edu.in


Slide Content

PRESENTED BY:
ANSHUSHARMA
Object Oriented Using Java -
Generic in Java

GENERICS IN JAVA
GenericsinJavaissimilartotemplatesin
C++.Theideaistoallowtype(Integer,
String,…etcanduserdefinedtypes)tobea
parametertomethods,classesand
interfaces.Forexample,classeslike
HashSet,ArrayList,HashMap,etcuse
genericsverywell.Wecanusethemforany
type.

GENERIC CLASS
weuse<>tospecifyparametertypesingenericclass
creation.Tocreateobjectsofgenericclass,weuse
followingsyntax.
//Tocreateaninstanceofgenericclass
BaseType<Type>obj=newBaseType<Type>()
Note:InParametertypewecannotuseprimitiveslike
'int','char'or'double'.

EXAMPLES: GENERIC CLASS
/ A Simple Java program to show working of user defined Generic classes
// We use < > to specify Parameter type
class Test<T>
{
// An object of type T is declared
T obj;
Test(T obj)
{
this.obj = obj;
}// constructor
public T getObject()
{
return this.obj;
}
}

EXAMPLE CONTD.
class Main
{
public static void main (String[] args)
{
// instance of Integer type
Test <Integer> iObj= new Test<Integer>(15);
System.out.println(iObj.getObject());
// instance of String type
Test <String> sObj=
new Test<String>("GeeksForGeeks");
System.out.println(sObj.getObject());
}
}

MULTIPLE TYPE PARAMETERS IN GENERIC
CLASSES
We can also pass multiple Type parameters in Generic classes.
// A Simple Java program to show multiple
// type parameters in Java Generics
// We use < > to specify Parameter type
class Test<T, U>
{
T obj1;// An object of type T
U obj2;//An object of type U
// constructor
Test(T obj1, U obj2)
{
this.obj1 = obj1;
this.obj2 = obj2;
}

EXAMPLE CONTD.
// To print objects of T and U
public void print()
{
System.out.println(obj1);
System.out.println(obj2);
}
}
// Driver class to test above
class Main
{
public static void main (String[] args)
{
Test <String, Integer> obj=
new Test<String, Integer>("GfG", 15);
obj.print();
}
}

GENERIC FUNCTIONS:
We can also write generic functions that can
be called with different types of arguments
based on the type of arguments passed to
generic method, the compiler handles each
method.

EXAMPLE:
// A Simple Java program to show working of user defined
// Generic functions
class Test
{
// A Generic method example
static <T> void genericDisplay(T element)
{
System.out.println(element.getClass().getName() +
" = " + element);
}

EXAMPLE CONTD.
// Driver method
public static void main(String[] args)
{
// Calling generic method with Integer argument
genericDisplay(11);
// Calling generic method with String argument
genericDisplay("GeeksForGeeks");
// Calling generic method with double argument
genericDisplay(1.0);
}
}

ADVANTAGES OF JAVA GENERICS
1. Code Reusability
Genericsallow us to write code that will
work with different types of data. For
example,
public <T> void genericsMethod(T data) {...}
Here, we have created a generics method.
This method can be used to perform
operations on integer data, string data and
so on.

ADVANTAGES CONTD.
2. Compile-time Type Checking
Thetypeparameterofgenericsprovidesinformation
aboutthetypeofdatausedinthegenericscode.
Hence,anyerrorcanbeidentifiedatcompiletimewhich
iseasiertofixthanruntimeerrors.Forexample,
//withoutusingGenerics
NormalClasslist=newNormalClass();//callsmethodof
NormalClass
list.display("String");
Intheabovecode,wehaveanormalclass.Wecallthe
methodnameddisplay()ofthisclassbypassingastring
data.
Here,thecompilerdoesnotknowifthevaluepassedin
theargumentiscorrectornot.

ADVANTAGES CONTD.
However, let's see what will happen if we use the
generics class instead.
// using Generics
GenericsClass<Integer> list = new
GenericsClass<>(); // calls method of GenericsClass
list2.display("String");
In the above code, we have a generics class. Here,
the type parameter indicates that the class is working
on Integer data. Hence when the string data is
passed in argument, the compiler will generate an
error.
Tags