Generics in Java is a mechanism for declaring types that can be used with objects of various types. Generics allow a single implementation to be used with multiple data types, which increases the flexibility and reusability of code.
There are two types of generics in Java:
- Class-level generics: These are generics that are applied to a class. For example, a generic class might be declared as
class MyClass<T> { ... }
, whereT
represents the type of object that will be used with the class.
Here’s an example of how you could use generics with a Car
class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
class Car<T> { private T model; public Car(T model) { this.model = model; } public T getModel() { return model; } } class Sedan extends Car<String> { public Sedan(String model) { super(model); } } class Hatchback extends Car<Integer> { public Hatchback(Integer model) { super(model); } } public static void main(String[] args) { Car<String> sedan = new Sedan("Sedan"); Car<Integer> hatchback = new Hatchback(1); System.out.println(sedan.getModel()); System.out.println(hatchback.getModel()); }  |
In this example, we have created a generic Car
class that can be used with either String
or Integer
types, depending on the implementation. The Sedan
and Hatchback
classes extend the Car
class and specify the type they will use (String
and Integer
, respectively). When creating instances of these classes, we can then access the model through the getModel
method and see that it returns the correct value for each type.Regenerate response
Method-level generics: These are generics that are applied to a method. For example, a generic method might be declared as public static <T> T myMethod(T t) { ... }
, where T
represents the type of object that will be passed to the method as an argument.
example:
Here’s an example of how you could use method-level generics with a Car
class:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
class Car { private Object model; public Car(Object model) { this.model = model; } public <T> T getModel(Class<T> clazz) { return clazz.cast(model); } } public static void main(String[] args) { Car sedan = new Car("Sedan"); Car hatchback = new Car(1); System.out.println(sedan.getModel(String.class)); System.out.println(hatchback.getModel(Integer.class)); } |
In this example, we have created a Car
class with a single model
property. The getModel
method is a generic method that takes a Class
object as an argument and returns an object of that type. When we create instances of the Car
class and call the getModel
method, we pass in the appropriate class for the type of object we want to retrieve (String.class
or Integer.class
). The method then uses the clazz.cast
method to cast the model
object to the correct type and return it.Regenerate response