SlideShare a Scribd company logo
Generics
Contents
• Introduction
• Benefits of Generics
• Generic Classes and Interfaces
• Generic Methods
• Wildcard Generic Types
• Restrictions on Generics
Introduction
• Enables to create classes, interfaces, and methods in which the type of data upon
which they operate is specified as a parameter.
• Introduced in Java by jdk 1.5.
• Generics means parameterized types.
• Generics add the type-safety.
• Generics add stability to your code by making more of your bugs detectable at
compile time.
WhyGenerics?
• The functionality of Gen class can be achieved without generics by specifying
Object type and using proper casting whenever required.
• Then why we use Generics?
• Java compiler does not have knowledge about the type of data actually stored in
NonGen. So:
• Explicit casts must be employed to retrieve the stored data.
• Several type mismatch errors cannot be found until run time.
WhyGenerics?
• Stronger type checks at compile time
• Elimination of casts
ArrayList list = new ArrayList();
list.add("hello");
String s = (String) list.get(0);
• Using generics:
List<String> list = new ArrayList<String>();
list.add("hello");
String s = list.get(0); // no cast
• Enablingprogrammers to implement generic algorithms.
We can implement generic algorithms that work on collections of different types, can
be customized, and are type safe and easier to read.
Example
GenericsWorkOnlywithObjects
• When declaring an instance of a generic type, the type argument passed to the
type parameter must be a class type.
• Gen<int> strOb = new Gen<int>(53);
• The above declaration is an error.
• A reference of one specific version of a generic type is not type compatible with
another version of the same generic type.
• iOb = strOb; // Wrong!
Generic Class
GeneralFormofGenericClass
• The generics syntax for declaring a generic class:
class class-name<type-param-list>
{ // ... }
• The syntax for declaring a reference to a generic class:
class-name<type-arg-list> var-name =
new class-name<type-arg-list>(cons-arg-list);
GenericClasswithMultipleType
Parameters
GenericClasswithMultipleType
Parameters
Problem
• Create a generic class that contains a method that returns the average of an array
of numbers of any type, including integers, floats, and doubles.
PossibleSolution
WhyError?
• The compiler has no way to know that you are intending to create Gen class
objects using only numeric types.
• When we try to compile Gen class, an error is reported that indicates that the
doubleValue( ) method is unknown.
• We need some way to tell the compiler that we intend to pass only numeric types
to T.
BoundedTypes
• Used to limit the types that can be passed to a type parameter.
• When specifying a type parameter, we can create an upper bound that declares
the super-class from which all type arguments must be derived.
<T extends superclass>
• A bound can include both a class type and one or more interfaces.
class Gen<T extends MyClass & MyInterface>
• Any type argument passed to T must be a subclass of MyClass and implement
MyInterface.
Solution
WILD CARD Generics
Example (comparingobjectvalues)
method compare(Stats<Integer>) in the type
Gen<Integer> is not applicable for the arguments
(Gen<Double>)
Gen<Integer> obj1
Memory representationof
objects
Gen<Double> obj2
Object of Gen<Integer>
required
wildcard generic (i.e. it accepts any type)
Solution
Problem
• Create a generic class Stats that contains a method sameAvg( ) that determines
whether two different Stats class objects contain arrays that yield the same
average or not; no matter what type of numeric data each object holds.
• For example, if one object contains the double values 1.0, 2.0, and 3.0, and the
other object contains the integer values 2, 1, and 3, then the averages will be the
same.
PossibleSolution
method same_Avg(Stats<Integer>) in the type Stats<Integer> is not
applicable for the arguments (Stats<Double>)
WhyError?
• It will work only with the objects of same type.
• if the invoking object is of type Stats<Integer>, then the parameter ob must also be
of type Stats<Integer>.
WildcardArgument
• The wildcardsimply matches the validity of object.
• The wildcardargument is specified by the ?, and it represents an unknown type.
boolean same_Avg(Stats<?> ob)
{
if(average() == ob.average())
return true;
return false;
}
• Important: It is important to understand that the wildcard does not affect what type of
Stats class objects can be created. This is governed by the extends clause in the Stats
class declaration. The wildcardsimply matches any valid Stats class object.
BoundedWildcards
• A bounded wildcard is especially important when you are creating a generic type
that will operate on a class hierarchy.
// Two-dimensional coordinates.
class TwoD {
int x, y;
TwoD(int a, int b) {
x = a;
y = b;
}
}
BoundedWildcards
// Three-dimensional coordinates.
class ThreeD extends TwoD {
int z;
ThreeD(int a, int b, int c) {
super(a, b);
z = c; }
}
// Four-dimensional coordinates.
class FourD extends ThreeD {
int t;
FourD(int a, int b, int c, int d) {
super(a, b, c);
t = d; }
}
BoundedWildcards
// This class holds an array of coordinate objects.
class Coords<T extends TwoD>
{
T[] coords;
Coords(T[] o) { coords = o; }
}
Notice that Coords specifies a type parameter bounded by TwoD.
static void showXY(Coords<?> c)
{
System.out.println("X Y Coordinates:");
for(int i=0; i < c.coords.length; i++)
System.out.println(c.coords[i].x + " " + c.coords[i].y);
System.out.println();
}
BoundedWildcards
Problem Starts if I want to create a methods showXYZ() for ThreeD and FourD Object.
static void showXYZ(Coords<? extends ThreeD> c)
{
System.out.println("X Y Z Coordinates:");
for(int i=0; i < c.coords.length; i++)
System.out.println(c.coords[i].x + " " + c.coords[i].y + " " + c.coords[i].z);
System.out.println();
}
Generic Method
GenericMethod
• It is possible to declare a generic method that uses one or more type parameters.
• Methods inside a generic class are automatically generic relative to the type
parameters.
• It is possible to create a generic method that is enclosed within a non-generic
class.
GenericMethod
• The type parameters are declared before the return type of the method.
• Generic methods can be either static or non-static.
<type-param-list> ret-type method-name(param-list) {…}
• Example:
static <T, V extends T> boolean isIn (T x, V[] y)
• This ability to enforce type safety is one of the most important advantages of
generic methods.
Example
Generics Module 2Generics ModuleGenerics Module 2
Generic Interfaces
GenericInterfaces
• Generic interfaces are specified just like generic classes.
GenericInterfaces
• Generic interfaces are specified just like generic classes.
• Example:
interface MinMax<T extends Comparable<T>>
{ T min(); T max(); }
• The implementing class must specify the same bound.
• Once the bound has been established, it need not to be specified again in the
implements clause.
GenericInterfaces
class MyClass<T extends Comparable<T>>implements MinMax <T extends
Comparable<T>>{ //Wrong
• In general, if a class implements a generic interface, then that class must also be
generic, at least to the extent that it takes a type parameter that is passed to the
interface. For example, the following attempt to declare MyClass is in error:
class MyClass implements MinMax<T>{ // Wrong!
• Because MyClass does not declare a type parameter, there is no way to pass one to
MinMax. In this case, the identifier T is simply unknown, and the compiler reports an
error. Of course, if a class implements a specific type of generic interface, such as
shown here:
class MyClass implements MinMax<Integer>{ // OK
GenericInterfaces
interface MinMax<T extends Comparable<T>>
{
T min();
T max();
}
class Myclass<T extends Comparable<T>> implements MinMax<T>
{
…
}
Example
Generic Constructors
Generics Module 2Generics ModuleGenerics Module 2
GenericConstructors
 It is possible for constructors to be generic, even if their class is not.
Example:
class GenCons
{
private double val;
<T extends Number> GenCons(T arg)
{
val = arg.doubleValue();
}
void show_val() { System.out.println("val: " + val);
}
}
Erasure
// Here, T is bound by Object by default.
class Gen<T> {
T ob; // here, T will be replaced by Object
Gen(T o) { ob = o; }
// Return ob.
T getob() { return ob; }
}
// Here, T is bound by String.
class GenStr<T extends String> {
T str; // here, T will be replaced by String
GenStr(T o) { str = o; }
T getstr() { return str; }
}
erasure
class Gen extends java.lang.Object{
java.lang.Object ob;
Gen(java.lang.Object);
java.lang.Object getob();
}
class GenStr extends java.lang.Object{
java.lang.String str;
GenStr(java.lang.String);
java.lang.String getstr();
}
SomeGeneric Restrictions
Type Parameters Can’t Be Instantiated
// Can't create an instance of T.
class Gen<T>
{
T ob;
Gen()
{
ob = new T(); // Illegal!!!
}
}
SomeGeneric Restrictions
Restrictions on Static Members
class Wrong<T>
{
// Wrong, no static variables of type T.
static T ob;
// Wrong, no static method can use T.
static T getob() {
return ob;
}
SomeGeneric Restrictions
• Generic Array Restrictions
• // vals = new T[10]; // can't create an array of T
• // Gen<Integer> gens[] = new Gen<Integer>[10]; // Wrong!
• it’s valid to declare a reference to an array of type.
• cannot create generic exception classes.
• Cannot Instantiate Generic Types with Primitive Types
• Pair<int, char> p = new Pair<>(8, 'a');
• Cannot Create, Catch, or Throw Objects of Parameterized Types
Generics Module 2Generics ModuleGenerics Module 2

More Related Content

PPTX
Generics Module 2Generics Module Generics Module 2.pptx
PPTX
21CS642 Module 2 Generics PPT.pptx VI SEM CSE
PPT
GenericsFinal.ppt
PPT
Generic
PPT
Generics in java
PDF
Generic Programming
PPTX
Module 4_CSE3146-Advanced Java Programming-Anno_Lambda-PPTs.pptx
PPT
Jdk1.5 Features
Generics Module 2Generics Module Generics Module 2.pptx
21CS642 Module 2 Generics PPT.pptx VI SEM CSE
GenericsFinal.ppt
Generic
Generics in java
Generic Programming
Module 4_CSE3146-Advanced Java Programming-Anno_Lambda-PPTs.pptx
Jdk1.5 Features

Similar to Generics Module 2Generics ModuleGenerics Module 2 (20)

PPTX
PPTX
Java generics final
PPTX
Java Generics
PPTX
PPTX
C# Generics
PPTX
Generic Programming in java
PPTX
Back-2-Basics: .NET Coding Standards For The Real World (2011)
PDF
Javase5generics
PPTX
Java fundamentals
PDF
Intake 38 2
PPTX
Presentation 4th
PDF
Intake 37 2
PDF
Generics and collections in Java
PPTX
Generic Collections and learn how to use it
PPT
Unit iii
PPTX
TEMPLATES in C++ are one of important topics in Object Oriented Programming
PPT
Generic Types in Java (for ArtClub @ArtBrains Software)
PPT
UNIT III.ppt
Java generics final
Java Generics
C# Generics
Generic Programming in java
Back-2-Basics: .NET Coding Standards For The Real World (2011)
Javase5generics
Java fundamentals
Intake 38 2
Presentation 4th
Intake 37 2
Generics and collections in Java
Generic Collections and learn how to use it
Unit iii
TEMPLATES in C++ are one of important topics in Object Oriented Programming
Generic Types in Java (for ArtClub @ArtBrains Software)
UNIT III.ppt
Ad

Recently uploaded (20)

PPTX
Welding lecture in detail for understanding
PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PPTX
Construction Project Organization Group 2.pptx
PDF
Digital Logic Computer Design lecture notes
PPTX
UNIT 4 Total Quality Management .pptx
PPTX
Foundation to blockchain - A guide to Blockchain Tech
PDF
Model Code of Practice - Construction Work - 21102022 .pdf
PDF
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
PPTX
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
PPTX
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
PPTX
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
PPTX
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
PPTX
CYBER-CRIMES AND SECURITY A guide to understanding
PPT
Project quality management in manufacturing
PPTX
UNIT-1 - COAL BASED THERMAL POWER PLANTS
PDF
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
PPTX
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
PPT
CRASH COURSE IN ALTERNATIVE PLUMBING CLASS
PPTX
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
DOCX
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
Welding lecture in detail for understanding
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
Construction Project Organization Group 2.pptx
Digital Logic Computer Design lecture notes
UNIT 4 Total Quality Management .pptx
Foundation to blockchain - A guide to Blockchain Tech
Model Code of Practice - Construction Work - 21102022 .pdf
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
FINAL REVIEW FOR COPD DIANOSIS FOR PULMONARY DISEASE.pptx
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
CYBER-CRIMES AND SECURITY A guide to understanding
Project quality management in manufacturing
UNIT-1 - COAL BASED THERMAL POWER PLANTS
PRIZ Academy - 9 Windows Thinking Where to Invest Today to Win Tomorrow.pdf
M Tech Sem 1 Civil Engineering Environmental Sciences.pptx
CRASH COURSE IN ALTERNATIVE PLUMBING CLASS
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
Ad

Generics Module 2Generics ModuleGenerics Module 2

  • 2. Contents • Introduction • Benefits of Generics • Generic Classes and Interfaces • Generic Methods • Wildcard Generic Types • Restrictions on Generics
  • 3. Introduction • Enables to create classes, interfaces, and methods in which the type of data upon which they operate is specified as a parameter. • Introduced in Java by jdk 1.5. • Generics means parameterized types. • Generics add the type-safety. • Generics add stability to your code by making more of your bugs detectable at compile time.
  • 4. WhyGenerics? • The functionality of Gen class can be achieved without generics by specifying Object type and using proper casting whenever required. • Then why we use Generics? • Java compiler does not have knowledge about the type of data actually stored in NonGen. So: • Explicit casts must be employed to retrieve the stored data. • Several type mismatch errors cannot be found until run time.
  • 5. WhyGenerics? • Stronger type checks at compile time • Elimination of casts ArrayList list = new ArrayList(); list.add("hello"); String s = (String) list.get(0); • Using generics: List<String> list = new ArrayList<String>(); list.add("hello"); String s = list.get(0); // no cast • Enablingprogrammers to implement generic algorithms. We can implement generic algorithms that work on collections of different types, can be customized, and are type safe and easier to read.
  • 7. GenericsWorkOnlywithObjects • When declaring an instance of a generic type, the type argument passed to the type parameter must be a class type. • Gen<int> strOb = new Gen<int>(53); • The above declaration is an error. • A reference of one specific version of a generic type is not type compatible with another version of the same generic type. • iOb = strOb; // Wrong!
  • 9. GeneralFormofGenericClass • The generics syntax for declaring a generic class: class class-name<type-param-list> { // ... } • The syntax for declaring a reference to a generic class: class-name<type-arg-list> var-name = new class-name<type-arg-list>(cons-arg-list);
  • 12. Problem • Create a generic class that contains a method that returns the average of an array of numbers of any type, including integers, floats, and doubles.
  • 14. WhyError? • The compiler has no way to know that you are intending to create Gen class objects using only numeric types. • When we try to compile Gen class, an error is reported that indicates that the doubleValue( ) method is unknown. • We need some way to tell the compiler that we intend to pass only numeric types to T.
  • 15. BoundedTypes • Used to limit the types that can be passed to a type parameter. • When specifying a type parameter, we can create an upper bound that declares the super-class from which all type arguments must be derived. <T extends superclass> • A bound can include both a class type and one or more interfaces. class Gen<T extends MyClass & MyInterface> • Any type argument passed to T must be a subclass of MyClass and implement MyInterface.
  • 18. Example (comparingobjectvalues) method compare(Stats<Integer>) in the type Gen<Integer> is not applicable for the arguments (Gen<Double>)
  • 20. wildcard generic (i.e. it accepts any type) Solution
  • 21. Problem • Create a generic class Stats that contains a method sameAvg( ) that determines whether two different Stats class objects contain arrays that yield the same average or not; no matter what type of numeric data each object holds. • For example, if one object contains the double values 1.0, 2.0, and 3.0, and the other object contains the integer values 2, 1, and 3, then the averages will be the same.
  • 22. PossibleSolution method same_Avg(Stats<Integer>) in the type Stats<Integer> is not applicable for the arguments (Stats<Double>)
  • 23. WhyError? • It will work only with the objects of same type. • if the invoking object is of type Stats<Integer>, then the parameter ob must also be of type Stats<Integer>.
  • 24. WildcardArgument • The wildcardsimply matches the validity of object. • The wildcardargument is specified by the ?, and it represents an unknown type. boolean same_Avg(Stats<?> ob) { if(average() == ob.average()) return true; return false; } • Important: It is important to understand that the wildcard does not affect what type of Stats class objects can be created. This is governed by the extends clause in the Stats class declaration. The wildcardsimply matches any valid Stats class object.
  • 25. BoundedWildcards • A bounded wildcard is especially important when you are creating a generic type that will operate on a class hierarchy. // Two-dimensional coordinates. class TwoD { int x, y; TwoD(int a, int b) { x = a; y = b; } }
  • 26. BoundedWildcards // Three-dimensional coordinates. class ThreeD extends TwoD { int z; ThreeD(int a, int b, int c) { super(a, b); z = c; } } // Four-dimensional coordinates. class FourD extends ThreeD { int t; FourD(int a, int b, int c, int d) { super(a, b, c); t = d; } }
  • 27. BoundedWildcards // This class holds an array of coordinate objects. class Coords<T extends TwoD> { T[] coords; Coords(T[] o) { coords = o; } } Notice that Coords specifies a type parameter bounded by TwoD. static void showXY(Coords<?> c) { System.out.println("X Y Coordinates:"); for(int i=0; i < c.coords.length; i++) System.out.println(c.coords[i].x + " " + c.coords[i].y); System.out.println(); }
  • 28. BoundedWildcards Problem Starts if I want to create a methods showXYZ() for ThreeD and FourD Object. static void showXYZ(Coords<? extends ThreeD> c) { System.out.println("X Y Z Coordinates:"); for(int i=0; i < c.coords.length; i++) System.out.println(c.coords[i].x + " " + c.coords[i].y + " " + c.coords[i].z); System.out.println(); }
  • 30. GenericMethod • It is possible to declare a generic method that uses one or more type parameters. • Methods inside a generic class are automatically generic relative to the type parameters. • It is possible to create a generic method that is enclosed within a non-generic class.
  • 31. GenericMethod • The type parameters are declared before the return type of the method. • Generic methods can be either static or non-static. <type-param-list> ret-type method-name(param-list) {…} • Example: static <T, V extends T> boolean isIn (T x, V[] y) • This ability to enforce type safety is one of the most important advantages of generic methods.
  • 35. GenericInterfaces • Generic interfaces are specified just like generic classes.
  • 36. GenericInterfaces • Generic interfaces are specified just like generic classes. • Example: interface MinMax<T extends Comparable<T>> { T min(); T max(); } • The implementing class must specify the same bound. • Once the bound has been established, it need not to be specified again in the implements clause.
  • 37. GenericInterfaces class MyClass<T extends Comparable<T>>implements MinMax <T extends Comparable<T>>{ //Wrong • In general, if a class implements a generic interface, then that class must also be generic, at least to the extent that it takes a type parameter that is passed to the interface. For example, the following attempt to declare MyClass is in error: class MyClass implements MinMax<T>{ // Wrong! • Because MyClass does not declare a type parameter, there is no way to pass one to MinMax. In this case, the identifier T is simply unknown, and the compiler reports an error. Of course, if a class implements a specific type of generic interface, such as shown here: class MyClass implements MinMax<Integer>{ // OK
  • 38. GenericInterfaces interface MinMax<T extends Comparable<T>> { T min(); T max(); } class Myclass<T extends Comparable<T>> implements MinMax<T> { … }
  • 42. GenericConstructors  It is possible for constructors to be generic, even if their class is not. Example: class GenCons { private double val; <T extends Number> GenCons(T arg) { val = arg.doubleValue(); } void show_val() { System.out.println("val: " + val); } }
  • 43. Erasure // Here, T is bound by Object by default. class Gen<T> { T ob; // here, T will be replaced by Object Gen(T o) { ob = o; } // Return ob. T getob() { return ob; } } // Here, T is bound by String. class GenStr<T extends String> { T str; // here, T will be replaced by String GenStr(T o) { str = o; } T getstr() { return str; } }
  • 44. erasure class Gen extends java.lang.Object{ java.lang.Object ob; Gen(java.lang.Object); java.lang.Object getob(); } class GenStr extends java.lang.Object{ java.lang.String str; GenStr(java.lang.String); java.lang.String getstr(); }
  • 45. SomeGeneric Restrictions Type Parameters Can’t Be Instantiated // Can't create an instance of T. class Gen<T> { T ob; Gen() { ob = new T(); // Illegal!!! } }
  • 46. SomeGeneric Restrictions Restrictions on Static Members class Wrong<T> { // Wrong, no static variables of type T. static T ob; // Wrong, no static method can use T. static T getob() { return ob; }
  • 47. SomeGeneric Restrictions • Generic Array Restrictions • // vals = new T[10]; // can't create an array of T • // Gen<Integer> gens[] = new Gen<Integer>[10]; // Wrong! • it’s valid to declare a reference to an array of type. • cannot create generic exception classes. • Cannot Instantiate Generic Types with Primitive Types • Pair<int, char> p = new Pair<>(8, 'a'); • Cannot Create, Catch, or Throw Objects of Parameterized Types