0% found this document useful (0 votes)
4 views24 pages

Lecture 10 Generic

The document discusses generic classes and methods in Java, highlighting their ability to create methods and classes that can operate on various data types while ensuring compile-time type safety. It provides examples of generic methods, classes, and wildcards, demonstrating their implementation and use cases. Additionally, it covers the benefits of using generics, such as reducing code redundancy and enhancing type safety.

Uploaded by

aoe7289
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views24 pages

Lecture 10 Generic

The document discusses generic classes and methods in Java, highlighting their ability to create methods and classes that can operate on various data types while ensuring compile-time type safety. It provides examples of generic methods, classes, and wildcards, demonstrating their implementation and use cases. Additionally, it covers the benefits of using generics, such as reducing code redundancy and enhancing type safety.

Uploaded by

aoe7289
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

Object-Oriented

Programming
IT069IU
Lecture 10
Generic Classes and Methods

Dr. Huynh Tan Quoc


Introduction

 Generic methods and generic classes(and interfaces) enable you

to specify, with a single method declaration, a set of related

methods, or with a single class declaration, a set of related

types, respectively.

 Generics also provide compile-time type safety that allows you

to catch invalid types at compile time.

2
Motivation for Generic Methods
 Overloaded methods are often used to perform similar

operations on different types of data.

 Study each printArray method.

◦Note that the type array element type appears in each

method’s header and for-statement header.

◦If we were to replace the element types in each method with a

generic name—T by convention—then all three methods would

look like the one in Fig.21.2.


3
Motivation for Generic Methods

4
Motivation for Generic Methods

5
Motivation for Generic Methods

6
Generic Methods: Implementation and
Complie-Time Translation
 If the operations performed by several overloaded methods are
identical for each argument type, the overloaded methods can
be more compactly and conveniently coded using a generic-
method.
 You can write a single generic method declaration that can be
called with arguments of different types.
 Based on the types of the arguments passed to the generic
method, the compiler handles each method call appropriately.
 Line 22 begins method printArray’s declaration.

7
Generic Methods: Implementation and
Complie-Time Translation

8
Generic Methods: Implementation and
Complie-Time Translation

9
Java Generic Type

 The most commonly used type parameter names are:

 E - Element (used extensively by the Java Collections Framework, for

example ArrayList, Set etc.)

 K - Key (Used in Map)

 N - Number

 T - Type

 V - Value (Used in Map)

 S,U,V etc. - 2nd, 3rd, 4th types

11
Java Generic Method
class Test {
// A Generic method example
static <T> void genericDisplay(T element)
{
System.out.println(element.getClass().getName()
+ " = " + element);
}

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);
}
}
12
Java Generic Class
public class KeyValuePair<K, V> {
private K key;
private V value;
public KeyValuePair(K key, V value) {
this.key = key;
this.value = value;
}
public K getKey() {
return key;
}
public void setKey(K key) {
this.key = key;
}
public V getValue() {
return value;
}
public void setValue(V value) {
this.value = value;
}
13
}
Java Generic Class

public class KeyValuePairExample {

public static void main(String[] args) {

KeyValuePair<String, Integer> entry = new KeyValuePair<String, Integer>("gpcoder",

123456789);
String name = entry.getKey();
Integer id = entry.getValue();

System.out.println("Name = " + name + ", Id = " + id); // Name = gpcoder, Id =

123456789
}
}

14
Java Generic Classes and Inheritance
 Example 1:

public class ContactEntry extends KeyValuePair<String, Integer> {

public ContactEntry(String key, Integer value) {


super(key, value);
}

public class ContactEntryExample {


public static void main(String[] args) {
ContactEntry entry = new ContactEntry("gpcoder", 123456789);
String name = entry.getKey();
Integer id = entry.getValue();
System.out.println("Name = " + name + ", Id = " + id); // Name = gpcoder, Id = 123456789
}
}
15
Java Generic Classes and Inheritance
 Example 2:
public class ContactEntry2<V> extends KeyValuePair<String, V> {

public ContactEntry2(String key, V value) {


super(key, value);
}

 Example 3:
public class ContactEntry3<K, V> extends KeyValuePair<K, V> {

public ContactEntry3(K key, V value) {


super(key, value);
}

} 16
Java Generic Classes and Inheritance
 Example 4:
public class ContactEntry4<K, V, T> extends KeyValuePair<K, V> {

private T obj;

public ContactEntry4(K key, V value, T obj) {


super(key, value);
this.obj = obj;
}

public T getObj() {
return obj;
}

public void setObj(T obj) {


this.obj = obj;
}
17
}
Java Generic Classes and Interface
 Interface: public interface GenericInteface<T> {

void setobj(T obj);


T getobj();
}

 Class: public class GenericImpl<T> implements GenericInterface<T> {


T obj
public void setobj(T obj) {
This.obj=obj;
}
public T getobj(T obj) {

Return obj
}

18
Java Generic Classes and Interface
 Interface:

public class GenericDaoExample {

public static void main(String[] args) {


GenericImplement<Integer> myNum=new GenericImplement<Integer>();
myNum.setobj(100);
System.out.println("my number is :"+myNum.getobj());
GenericImplement<String> myText=new GenericImplement<String>();
myText.setobj("Hello");
System.out.println("my text is :"+myText.getobj());

}
}

19
Java Generic Array
public class GenericArray<T> {
private T[] array;

public GenericArray(int size) {


// Creating a generic array using reflection
array = (T[]) new Object[size];
}

public void setElement(int index, T value) {


array[index] = value;
}

public T getElement(int index) {


return array[index];
}

public static void main(String[] args) {


GenericArray<String> stringArray = new GenericArray<>(5);
stringArray.setElement(0, "Java");
stringArray.setElement(1, "is");
stringArray.setElement(2, "awesome");

System.out.println("Element at index 1: " + stringArray.getElement(1));


} 20
}
Java Generic Wildcard
We can use wildcards with bounds in three ways:

 Unbounded Wildcards: GenericType<?>


– represents a list of any type

 Upper Bounded Wildcards: GenericType<? extends SuperClass>


– specify that a method accepts a type and all its subclasses.

 Lower Bounded Wildcards: GenericType<? super SubClass>


– specify that a method accepts a type and all its superclasses

21
Java Generic Wildcard
 Unbounded Wildcards: GenericType<?>
– represents a list of any type
import java.util.*;
public class Unbound {
public static void printCollection(Collection<?> c) {
for (Object e : c) {
System.out.println(e);
}
}
public static void main(String[] args) {
Collection<String> collection = new ArrayList<>();
collection.add("ArrayList Collection");
printCollection(collection);
Collection<String> collection2 = new LinkedList<>();
collection2.add("LinkedList Collection");
printCollection(collection2);
Collection<String> collection3 = new HashSet<>();
collection3.add("HashSet Collection");
printCollection(collection3);
}
} 22
Java Generic Wildcard
 Upper Bounded Wildcards: GenericType<? extends SuperClass>
– specify that a method accepts a type and all its subclasses.
import java.util.*;
public class UpperBound {
static void processElements(List<? extends Number> a) {
for (Object element : a) {
System.out.println(element);
}}
public static void main(String[] args) {
// ArrayList Containing Integers
List<Integer> a1 = new ArrayList<>();
a1.add(10);
a1.add(20);
a1.add(30);
processElements(a1);
// ArrayList Containing Longs
List<Long> a2 = new ArrayList<>();
a2.add(100L);
a2.add(200L);
a2.add(300L);
23
processElements(a2);
Java Generic Wildcard
// Arraylist containing Doubles
List<Double> a3 = new ArrayList<>();
a3.add(21.35);
a3.add(56.47);
a3.add(78.12);
processElements(a3);
// Arraylist containing Strings
List<String> a4 = new ArrayList<>();
a4.add("One");
a4.add("Two");
a4.add("Three");
// This will not work
//processElements(a4); // Compile time
error
}
}

24
Java Generic Wildcard
 Lower Bounded Wildcards: GenericType<? super SubClass>
– specify that a method accepts a type and all its superclasses
public class LowerBound {
static void processElements(List<? super Integer> a) {
for (Object element : a) {
System.out.println(element);
}}
public static void main(String[] args) {
// ArrayList Containing Integers
List<Integer> a1 = new ArrayList<>();
a1.add(10);
a1.add(20);
a1.add(30);
processElements(a1);
// ArrayList Containing Longs
List<Long> a2 = new ArrayList<>();
a2.add(100L);
a2.add(200L);
a2.add(300L);
//processElements(a2); // compiler error 25
}}

You might also like