https://github.com/nisanth2004/java-generics
This repository covers essential concepts and examples, from basic generics syntax to advanced type constraints.
https://github.com/nisanth2004/java-generics
datatype devlopment devops genrics java spring springboot t type
Last synced: 25 days ago
JSON representation
This repository covers essential concepts and examples, from basic generics syntax to advanced type constraints.
- Host: GitHub
- URL: https://github.com/nisanth2004/java-generics
- Owner: Nisanth2004
- Created: 2024-11-06T12:12:19.000Z (over 1 year ago)
- Default Branch: main
- Last Pushed: 2024-11-08T11:39:44.000Z (over 1 year ago)
- Last Synced: 2025-02-28T10:38:26.733Z (over 1 year ago)
- Topics: datatype, devlopment, devops, genrics, java, spring, springboot, t, type
- Language: Java
- Homepage:
- Size: 9.77 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# Java Generics Example
Generics in Java allow us to create classes, interfaces, and methods with type parameters, improving type safety and reducing the need for explicit casting. This example demonstrates the basics of using generics in Java to handle different data types in a type-safe way.
## Why Use Generics?
- **Avoid `ClassCastException`**: Prevents errors that occur when trying to cast incompatible types.
- **Type Safety**: Ensures that only the specified type can be used, catching type errors at compile-time.
- **No Explicit Casting Needed**: Removes the need to cast objects to specific types.
## Example: Generic Class `GenricsDemo`
The `GenricsDemo` class is a generic class that can accept any data type (like `String`, `Integer`, etc.). It stores the object of type `T` and prints the class type of the object.
### Code
```java
// Generic class with type parameter
public class GenricsDemo {
T t;
// Constructor to initialize the generic type
public GenricsDemo(T ob) {
this.t = ob;
}
// Method to display the object's class type
public void show() {
System.out.println("Class of the Object is: " + t.getClass().getTypeName());
}
}