3.A] What are Generics? Provide an example program.
Answer:
Generics in Java are a feature that allows you to define classes, interfaces, and methods with type parameters. This means you can create components that operate on objects of various types while providing compile-time type safety. Generics enable you to write more flexible and reusable code by allowing you to parameterize types.
Benefits of Generics:
- Type Safety: Prevents runtime type errors by checking types at compile-time.
- Code Reusability: Allows you to create classes, interfaces, and methods that can work with any type.
- Eliminates Casting: Removes the need for explicit type casting when retrieving elements from a collection.
Example Program: Using Generics
Let’s create a simple generic class and demonstrate its usage.
Step 1: Define a Generic Class
// Define a generic class with type parameter T class Box<T> { private T content; public void setContent(T content) { this.content = content; } public T getContent() { return content; } }
Explanation:
- The
Box
class has a type parameterT
. T
can be any type, and the class will operate on this type.setContent()
method sets the content of the box, andgetContent()
retrieves it.
Step 2: Use the Generic Class
public class GenericsExample { public static void main(String[] args) { // Create a Box for Integer Box<Integer> integerBox = new Box<>(); integerBox.setContent(123); System.out.println("Integer content: " + integerBox.getContent()); // Create a Box for String Box<String> stringBox = new Box<>(); stringBox.setContent("Hello Generics!"); System.out.println("String content: " + stringBox.getContent()); } }
Explanation:
Box<Integer>
: Creates aBox
instance that holdsInteger
values.Box<String>
: Creates aBox
instance that holdsString
values.- The
setContent()
andgetContent()
methods work with the type specified (Integer
orString
).
Output:
When you run the program, you will get the following output:
Integer content: 123 String content: Hello Generics!
Key Points:
- Generic Class: A class with a type parameter (
T
) that can be replaced with any type. - Type Safety: The compiler ensures that the type specified is consistent throughout the class.
- Code Reusability: The same
Box
class can be used with different types, reducing code duplication and increasing flexibility.
Generics are widely used in Java, especially with collections such as ArrayList
, HashMap
, and other container classes, allowing you to specify the type of elements they store.