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

Day17 Generics

Uploaded by

mohamedjaaved19
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)
7 views

Day17 Generics

Uploaded by

mohamedjaaved19
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/ 36

Generics

TNS India Foundation | ‹#›


Partners in Economic Transformation
Recap

● String - an object that represents a number of character values


● StringBuffer - It is used to create modifiable strings.
● String pool - It is the special area in the heap memory to store string objects.

TNS India Foundation | ‹#›


Partners in Economic Transformation
Quiz
Q1.What will be the output of below statements?
String s1= “abc”;
String s2=”def”;
System.out.println(s1.compareTo(s2));

A 0

B true

C -3

D false

TNS India Foundation | ‹#›


Partners in Economic Transformation
Quiz
Q1.What will be the output of below statements?
String s1= “abc”;
String s2=”def”;
System.out.println(s1.compareTo(s2));

A 0

B true

C -3

D false

TNS India Foundation | ‹#›


Partners in Economic Transformation
Quiz

Q2.Which of the following classes, you can create objects without using new
operator?

A StringBuilder

B String

C StringBuffer

D Object

TNS India Foundation | ‹#›


Partners in Economic Transformation
Quiz

Q2.which of the following classes, you can create objects without using new
operator?

A StringBuilder

B String

C StringBuffer

D Object

TNS India Foundation | ‹#›


Partners in Economic Transformation
Learning Objective

● Explore generics syntax in Java and review examples.


● Grasp the concept of generic classes for type-safe and reusable code.
● Understand the necessity of generics to address type safety and code flexibility.
● Learn about generic methods and their role in writing flexible code.
● Master the rules for declaring generic methods in Java.
● Understand unbounded wildcards for handling unknown types.
● Navigate the use of bounded wildcards to restrict types for precision.
● Grasp the application of lower-bounded wildcards for accepting specific types.
● Apply generics in practical scenarios to enhance code quality and adaptability.

TNS India Foundation | ‹#›


Partners in Economic Transformation
Hook

Can we reuse the same class to send message of type Employee

TNS India Foundation | ‹#›


Partners in Economic Transformation
Generics with syntax and example

● Generics is a mechanism by which a single piece of code can manipulate many


different data types without explicitly having a separate entity for each data type.
● The Java Generics allows us to create a single class, interface, and method that can
be used with different types of data (objects).
● Generics are used to check the type compatibility at the compile time and hence
removing the chances of occuring ClassCastException at run time.
● Generics, as the name suggests, is a general way of defining methods, definitions,
and collections so that they are not dependent on the data type supplied to them.

TNS India Foundation | ‹#›


Partners in Economic Transformation
● Generics allows programmer to create parameterized types Instances of such types
can be created by passing reference types.

TNS India Foundation | ‹#›


Partners in Economic Transformation
● They can function the same no matter what data type they use.
● Collections such as ArrayLists use generics extensively.
● Generics are generally declared in the “<>” brackets.

Syntax:

class Class_Name<T1, T2, T3 ... Tn>


{
//Generic Type or Parameterized type
}
Where T1, T2, T3 … Tn (T stands for Type) enclosed within angle brackets (<>) are called
type parameters and class ‘Class_Name‘ is called generic type or parameterized type.

TNS India Foundation | ‹#›


Partners in Economic Transformation
Generic Class

● A class that is declared generic type is called generic class in Java. It is type-safe and
can act upon any data type.
● A generic class is also called “parameterized types” because it uses a parameter that
determines which data type it should work upon.
● Java Generic class is designed to work upon objects. Hence, it cannot work with
primitive data types.
● Generic class works on any kind of data type, we cannot specify a specific data type
such as Integer, String, etc.
class Myclass<T>
{
// class code
}

TNS India Foundation | ‹#›


Partners in Economic Transformation
Example

TNS India Foundation | ‹#›


Partners in Economic Transformation
Hands on Coding

TNS India Foundation | ‹#›


Partners in Economic Transformation
TNS India Foundation | ‹#›
Partners in Economic Transformation
Need of Generics

● Errors are integral part of coding. Some errors occur at compile time and some errors
occur at run time.
● Errors which occur at compile time can be easily identified and can be removed. But,
run time errors occur when an application is running in real time. If they happen, they
cause abrupt termination of an application.
● ClassCastException is also such an exception which happens only at run time.
● It occurs when data of one type cannot be casted to another type.
● You will never get a single clue about this exception during compilation.

TNS India Foundation | ‹#›


Partners in Economic Transformation
Activity

TNS India Foundation | ‹#›


Partners in Economic Transformation
TNS India Foundation | ‹#›
Partners in Economic Transformation
Generic Method

● A method that takes generic type parameters is called generic method in Java.
● A generic type can be applied for the static method. We can define a generic method
by putting generic type parameter <T> before the method return type and immediately
after the keyword static.
● The general syntax to declare a generic method in Java is as follows:
public static <T> void display(T[ ] list)
{
// method code;
}

TNS India Foundation | ‹#›


Partners in Economic Transformation
Rules to declare Generic Methods in Java

● You should explicitly specify type parameters before the actual name of the return
type of the method. The type parameter is delimited by angle brackets.

Example: <T>

● You should also include the type parameters in the declaration of the program and
separate them with commas.
● A type parameter specifies a generic type name in the method.
● All the type parameters are only useful when they have to declare reference types.
Remember that the type parameters cannot denote primitive data types such as
int, float, String etc.

TNS India Foundation | ‹#›


Partners in Economic Transformation
Hands on Coding

TNS India Foundation | ‹#›


Partners in Economic Transformation
Unbounded Wildcards
● An unbounded wildcard is represented by <?>. It means the data type is unknown.
● For instance, consider a method that prints the contents of a list:

public void printList(List<?> list)


{
for (Object item : list)
{
System.out.println(item);
}

TNS India Foundation | ‹#›


Partners in Economic Transformation
Bounded Wildcards
● There are instances where you might want to restrict the types that a method accepts.
This is where bounded wildcards come into play.
● Upper Bounded Wildcards use the extends keyword.
● For example, a method processing numbers might only want to accept lists of Number
or its subclasses.
public void processNumbers(List<? extends Number> numbers)
{
// Process the list here
}

TNS India Foundation | ‹#›


Partners in Economic Transformation
Lower Bound

● Lower Bounded Wildcards use the super keyword.


● They restrict the unknown type to be a particular type or a superclass of that type.

public void addIntegers(List<? super Integer> list)


{
list.add(new Integer(50)); // Adds the integer to the list
}

TNS India Foundation | ‹#›


Partners in Economic Transformation
Hands on Coding

TNS India Foundation | ‹#›


Partners in Economic Transformation
Uses of Generics

TNS India Foundation | ‹#›


Partners in Economic Transformation
Hands on Coding

TNS India Foundation | ‹#›


Partners in Economic Transformation
Quiz

Q1.What is the main purpose of using generics in Java?

A To improve runtime performance

B To enforce type safety

To reduce code readability


C

D To eliminate the need for comments

TNS India Foundation | ‹#›


Partners in Economic Transformation
Quiz

Q1.What is the main purpose of using generics in Java?

A To improve runtime performance

B To enforce type safety

To reduce code readability


C

D To eliminate the need for comments

TNS India Foundation | ‹#›


Partners in Economic Transformation
Quiz

Q2. Which wildcard is used to represent an unknown type in generics?

A Unbounded Wildcard (?)

B Upper Bounded Wildcard (? extends T)

C Lower Bounded Wildcard (? super T)

D Generic Wildcard (*)

TNS India Foundation | ‹#›


Partners in Economic Transformation
Quiz

Q2. Which wildcard is used to represent an unknown type in generics?

A Unbounded Wildcard (?)

B Upper Bounded Wildcard (? extends T)

C Lower Bounded Wildcard (? super T)

D Generic Wildcard (*)

TNS India Foundation | ‹#›


Partners in Economic Transformation
Summary

● Generics - single piece of code can manipulate many different data types without
explicitly having a separate entity for each data type.
● Generics - It is declared in the “<>” brackets
● Generic class - It is designed to work upon objects. Hence, it cannot work with primitive
data types.
● Generic Method- A method that takes generic type parameters.
● Unbounded WildCard-An unbounded wildcard is represented by <?>.
● Lower Wildcard - It use the super keyword.

TNS India Foundation | ‹#›


Partners in Economic Transformation
Assignment Question

Generic Inventory System

Objective:

Create a generic inventory system that can manage different types of products using
Java generics.

Requirements:

Product Class:

Create a Product class with attributes like id (String), name (String), and price
(double).
TNS India Foundation | ‹#›
Partners in Economic Transformation
Inventory Class:

● Implement a generic Inventory class that can manage various types of products.
● The inventory should use a data structure to store products (e.g., ArrayList).

Add and Remove Products:

Implement methods to add and remove products from the inventory.

Display Inventory:

Create a method to display the current inventory, including product details.

TNS India Foundation | ‹#›


Partners in Economic Transformation
Generic Methods:

Use generic methods to handle different types of products in the inventory.

Test the System:

● Create a test program to demonstrate the functionality of the generic inventory system.
● Add products of different types (e.g., electronics, clothing) and display the inventory.

TNS India Foundation | ‹#›


Partners in Economic Transformation
Let’s Reflect -

1. What is your major learning from today’s session?


2. How are you going to use this learning in your journey on the job?

TNS India Foundation | ‹#›


Partners in Economic Transformation

You might also like