unit-4 oop
unit-4 oop
Generic is a mechanism for creating a general model in which generic methods and generic
classes enable programmers to specify a single method (or a set of related methods) and single
class (or a set of related classes) for performing the desired task.
For example -
Suppose we want to create a stack and if we create a stack of integers then it will store only the
integer elements, if we try to push any string or any double type element then a compile time
error will occur. If we want to push any string then we need to create a separate stack, separate
class and separate methods for handling the String elements. Same is true for the elements of
any other data type. This results in complex code building. To avoid such complexity, a
concept of generic programming is introduced.
What is the need for Generic?
Following features show the importance of generics in Java.
1. It saves the programmers burden of creating separate methods for handling data
belonging to different data types.
2. It allows the code reusability.
3. Compact code can be created.
Review Question
Generic method allows a programmer to write a generalised method for the methods of
different data types.
Suppose we want to print an array of integer, float and character type elements then normally
we write three different methods performing the corresponding task. The object oriented
feature of Java allows us to make use of same function name. This idea is illustrated in
following Java program –
Java Program[OverloadProg1.java]
import java.io.*;
import java.util.*;
public class OverloadProg1
{
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Object Oriented Programming 7-3 Generic Programming
Java Program[OverloadProg2.java]
import java.io.*;
import java.util.*;
public class OverloadProg2
{
public static < T > void display(T[] a) //Generic Method is created
{
for(int i=0;i<5;i++)
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Object Oriented Programming 7-4 Generic Programming
System.out.printf(" %s",a[i]);
}
public static void main(String[] args)
{
float[] dbl_a={11,22,33,44,55};
int[] int_a={1,2,3,4,5};
char[] char_a={'A','B','C','D','E'};
System.out.println("\n The Float elements are ...");
display( dbl_a );
System.out.println("\n The Integer elements are ...");
display( int_a );
System.out.println("\n The character elements are ...");
display( char_a );
}
}
Output
The Float elements are ...
11.00 22.00 33.00 44.00 55.00
The Integer elements are ...
12345
The character elements are ...
ABCDE
Ex. 7.2.1 : Write generic method for sorting an array of integer objects.
AU : May-19, Marks 6
Sol. :
private <E extends Comparable<E>>void bubbleSortG(E[] Arr) {
E temp;
for(int j = 1; j < Arr.length; j++) {
for(int i = 0; i < Arr.length - j; i++) {
if(Arr[i].compareTo(Arr[i+1]) > 0) {
temp = Arr[i];
Arr[i] = Arr[i+1];
Arr[i+1] = temp;
}
}
}
for(E i: Arr) {
System.out.print(" " + i);
}
}
Review Question
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Object Oriented Programming 7-5 Generic Programming
A generic class contains one or more variables of generic data type. Following is a simple
example which shows how to define the generic class .
public class Test<T>
{
public Test(){val=null;}
public Test(T val)
{
this.val=val;
}
public getVal()
{
return val;
}
public setVal()
{
val=newValue;
}
private T val; //variable defined as of genric type
}
The concept of generic class supports the idea of type-independency. Typical example of data
structure is stack. We can create a generic class for stack which allows us to insert integer,
character or any other data type elements using the same push and pop methods.
Ex. 7.3.1 : Create a generic class for the stack data structure. Your class must handle
integer and character type elements. Show clearly how will you handle the stack
empty condition
Sol. : We will create a generic class for stack data structure using following steps -
Java Program[Stack.java]
import java.util.*; //Supports the ArrayList
public class Stack<T> //T denotes any data type
{
public ArrayList<T> obj;
public Stack(int size) //Constructor will be invoked from main
{
obj=new ArrayList<T>(size);
}
public void push(T item) //Generic method for PUSH operation
{
obj.add(item);
}
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Object Oriented Programming 7-6 Generic Programming
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Object Oriented Programming 7-7 Generic Programming
E
D
Popping all the elements from integer stack
5
4
3
2
1
Performing one more pop for integer stack
Stack is Empty
null
Program Explanation
In the step 1 we have created a separate Java file, in which a class is written for defining the
generic methods push and pop. Note that it is necessary to define the constructor for this class
because it will then allow to initialize the class of appropriate data type.
In step 2 we are first creating the separate instances for each of these classes say cst and ist.
Then using these instances the generic push and pop methods will be invoked.
The output given in the step 2 is self explanatory.
Ex. 7.3.2 : Using generic classes, write a program to perform the following operations
on an array i) Add an element in the beginning/middle/end ii) Delete an element from
a given position
AU : May-14, Marks 16
Sol. :
import java.io.*;
import java.util.*; //Supports the ArrayList
class Arr<T> //T denotes any data type
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Object Oriented Programming 7-8 Generic Programming
{
public ArrayList<T> obj;
public Arr(int size) //Constructor will be invoked from main
{
obj=new ArrayList<T>(size);
}
public void insert(int index,T item) //Generic method for insert Operation
{
obj.add(index,item);
}
public void display()
{
System.out.print(" "+obj);
}
public T del(int index)//Generic method for delete Operation
{
return obj.remove(index);
}
}
public class ArrayGeneric
{
public static void main(String[] args)
{
int[] iArray={1,2,3,4,5};
Arr<Integer> iobj=new Arr<Integer>(10);
int i,index;
System.out.println("\n Array of integers is ...");
for(i=0;i<5;i++)
iobj.insert(i,iArray[i]);
iobj.display();
System.out.println("\n Inserting the elements in integer Array");
System.out.println("Enter the element to be inserted: ");
Scanner sc=new Scanner(System.in);
int item = sc.nextInt();
System.out.println("Enter the index at which the element is to be inserted: ");
index = sc.nextInt();
iobj.insert(index,item);
iobj.display();
System.out.println("\n Enter the index of the element to be deleted: ");
index = sc.nextInt();
iobj.del(index);
iobj.display();
double[] dArray={11.11,22.22,33.33,44.44,55.55};
Arr<Double> dobj=new Arr<Double>(10);
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Object Oriented Programming 7-9 Generic Programming
Review Questions
Many times it will be useful to limit the types that can be passed to type parameters. For
that purpose, bounded types are introduced in generics.
Using bounded types, we can make the objects of generic class to have data of specific
derived types.
For example, If we want a generic class that works only with numbers (like int, double,
float, long …..) then declare type parameter of that class as a bounded type to Number
class. Then while creating objects to that class you have to pass only Number types or it’s
subclass types as type parameters.
The syntax for declaring Bounded type parameters is
<T extends SuperClass>
This specifies that ‘T’ can only be replaced by ‘SuperClass’ or it’s sub classes.
For example
class Test<T extends Number> //Declaring Number class as upper bound of T
{
T t;
public Test(T t)
{
this.t = t;
}
public T getT()
{
return t;
}
}
public class BoundedTypeDemo
{
public static void main(String[] args)
{
//Creating object by passing Number as a type parameter
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Object Oriented Programming 7 - 11 Generic Programming
Ans. : A generic class contains one or more variables of generic data type. Following is a
simple example which shows how to define the generic class .
public class Test<T>
{
public Test(){val=null;}
public Test(T val)
{
this.val=val;
}
public getVal()
{ return val;
}
public setVal()
{
val=newValue;
}
private T val; //variable defined as of generic type
}
Q.4 Can generic be used with inheritance in several ways ? What are they ?
Ans. : Following are the ways by which generic can be used with inheritance -
Consider a class and a subclass such as Employee and Trainee . There are two pair classes
Pair<Employee> and Pair<Trainee> which do not possess an inheritance relation. That is,
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Object Oriented Programming 7 - 13 Generic Programming
Pair<Trainee> is not a subclass of Pair<Employee> even if these two classes are related to
each other.
The parameterised raw type can be converted to a raw type.
Ans. :
1. Due to the use of type parameter it saves the programmers burden of creating separate
methods for handling data belonging to different data types.
2. Due to type parameter the early error detection at compile time occurs. This avoids
crashing of the code(due to type incompatibility) at run time.
Ans. :
i) The virtual machine does not work with generic classes or generic methods. Instead it
makes uses raw types in which the raw types are replaced with ordinary java types.
Each type variable is replaced with its bound or with object, if it is not bounded. This
technique is called type erasure.
ii) In order to handle the type erasure methods the compiler has to generate bridge
methods in corresponding class.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge