0% found this document useful (0 votes)
12 views

unit-4 oop

Notes 2.

Uploaded by

jadu0044221
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

unit-4 oop

Notes 2.

Uploaded by

jadu0044221
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 12

Object Oriented Programming 7-2 Generic Programming

7.1 What is Generic Programming ?


AU : Dec.-13, Marks 4

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

1. Mention the motivations of generic programming


AU : Dec.-13, Marks 4

7.2 Generic Methods


AU : May-15, 19, Marks 8

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

public static void display(float[] a)


{
for(int i=0;i<5;i++)
System.out.printf(" %.2f",a[i]);
}
Note that the name
public static void display(int[] a)
of these three
{ functions is same
for(int i=0;i<5;i++) i.e. display
System.out.printf(" %d",a[i]);
}
public static void display(char[] a)
{
for(int i=0;i<5;i++)
System.out.printf(" %c",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
But if we override the generic methods then the code becomes more simplistic –

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

1. Explain about generic method with suitable example.


AU : May-15, Marks 8

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Object Oriented Programming 7-5 Generic Programming

7.3 Generic Classes


AU : May-14, CSE : Dec.-10,12,14, May-12, IT : May-13, Marks 16

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 -

Step 1 : Create a Java file named Stack.java as follows -

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

public T pop()//Generic method for POP operation


{
if(obj.isEmpty())
{
System.out.println("\n Stack is Empty");
return null;
}
return obj.remove(obj.size()-1);
}
}
Step 2 : Create another Java program in a separate file named StackGeneric.java. It is as given
below -
Java Program[StackGeneric.java]
import java.io.*;
import java.util.*;
public class StackGeneric
{
public static void main(String[] args)
Declaring integer and character values to be
{
int[] iArray={1,2,3,4,5}; pushed onto the stack.
char[] cArray={'A','B','C','D','E'};
ist is an instance for integer stack and cst is an
instance for character stack.
The Constructor Stack(size) will be invoked.
Stack<Integer> ist=new Stack<Integer>(5);
Stack<Character> cst=new Stack<Character>(5);

System.out.println("\n Pushing the elements in integer stack");


for(int i=0;i<5;i++)
ist.push(iArray[i]); Pushing onto the integer stack

System.out.println("\n Pushing the elements in character stack");


for(int i=0;i<5;i++) Pushing onto the character stack
cst.push(cArray[i]);

System.out.println("\n Popping two elements from character stack");


for(int i=0;i<2;i++) Popping from the
System.out.printf("\n%c",cst.pop()); character stack

System.out.println("\n Popping all the elements from integer stack");


for(int i=0;i<5;i++) Popping from the
System.out.printf("\n%d",ist.pop()); integer stack

®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Object Oriented Programming 7-7 Generic Programming

System.out.println("\n Performing one more pop for integer stack");


System.out.printf("\n%d",ist.pop());
}
} This pop operation
is to handle the
Output stack Empty
F:\>javac StackGeneric.java condition
F:\>java StackGeneric

Pushing the elements in integer stack

Pushing the elements in character stack

Popping two elements from character stack

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

System.out.println("\n Array of doubles is ...");


for(i=0;i<5;i++)
dobj.insert(i,dArray[i]);
dobj.display();
System.out.println("\n Inserting the elements in double Array");
System.out.println("Enter the element to be inserted: ");
sc=new Scanner(System.in);
double ditem = sc.nextDouble();
System.out.println("Enter the index at which the element is to be inserted: ");
index = sc.nextInt();
dobj.insert(index,ditem);
dobj.display();
System.out.println("\n Enter the index of the element to be deleted: ");
index = sc.nextInt();
dobj.del(index);
dobj.display();
}
}
Output
Array of integers is ...
[1, 2, 3, 4, 5]
Inserting the elements in integer Array
Enter the element to be inserted:
100
Enter the index at which the element is to be inserted:
2
[1, 2, 100, 3, 4, 5]
Enter the index of the element to be deleted:
4
[1, 2, 100, 3, 5]
Array of doubles is ...
[11.11, 22.22, 33.33, 44.44, 55.55]
Inserting the elements in double Array
Enter the element to be inserted:
111.222
Enter the index at which the element is to be inserted:
3
[11.11, 22.22, 33.33, 111.222, 44.44, 55.55]
Enter the index of the element to be deleted:
2
[11.11, 22.22, 111.222, 44.44, 55.55]
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Object Oriented Programming 7 - 10 Generic Programming

Review Questions

1. Explain the generic classes and generic methods with example.


AU : CSE : Dec.-10,12, May-12, IT : May-13, Marks 16
2. Explain in detail about generic classes and methods in java with suitable example.
AU : IT : May-13, Marks 16
3. Develop a Java program that will illustrate the use of Generic classes. Give self explanatory comments in
your program
AU : Dec.-14, Marks 8

7.4 Bounded Types


 While creating objects to generic classes we can pass any derived type as type parameters.

 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

Test<Number> obj1 = new Test<Number>(123);


System.out.println("The integer is: "+obj1.getT());
//While Creating object by passing String as a type parameter, it gives compile time
//error
Test<String> obj2 = new Test<String>("I am string"); //Compile time error
System.out.println("The string is: "+obj2.getT());
}
}
Review Question

1. Explain the use of bounded types in Generics with illustrative program.

7.5 Restrictions and Limitations


1. In Java, generic types are compile time entities. The runtime execution is possible only if
it is used along with raw type.
2. Primitive type parameters is not allowed for generic programming.
For example: Stack<int> is not allowed.
3. For the instances of generic class throw and catch instances are not allowed.
For example :
public class Test<T> extends Exception
{
//code // Error:can’t extend the Exception class
}
4. Instantiation of generic parameter T is not allowed.
For example :
new T() //Error
new T[10]
5. Arrays of parameterized types are not allowed.
For example :
new Stack<String>[10];//Error
6. Static fields and static methods with type parameters are not allowed.
Two Marks Questions with Answers

Q.1 Why generic programming is required ?


OR
What is the need for generic programming ?
AU : CSE : May-13, Dec.-18

Ans. : Following some reasons for the need of generic programming -


1. It saves the programmers burden of creating separate methods for handling data
belonging to different data types.
®
TECHNICAL PUBLICATIONS - An up thrust for knowledge
Object Oriented Programming 7 - 12 Generic Programming

2. It allows the code reusability.


3. Compact code can be created.
Q.2 List out motivation needed in generic programming.
Ans. :
1. 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.
2. It saves the programmers burden of creating separate methods for handling data
belonging to different data types.
3. It allows the code reusability.
4. Compact code can be created.
Q.3 With an example define a generic class. Or Describe generic classes.
AU : CSE : Dec.-12, 13, May-19

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.

 The generic classes can extend to implement other generic classes.


Q.5 List any two advantages of type parameters.
AU : May-11

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.

Q.6 State any two challenges of generic programming in virtual machine.


AU : IT : May-13

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

You might also like