Java Generic
Java Generic
Basic Examples
Generic Class Example: NEW
In this example, Box is a generic class that can hold a value of any type. The <T> in Box<T> is a type parameter, and it represents the type that will be specified when creating an instance of the Box class. Here's how you can use it:
Generic Class Example with supper class: NEW
In this example:
We have a generic class called StorageBox<T>, which extends a non-generic superclass Box<T>. T is the type parameter that is inherited from the superclass.
The StorageBox class has an additional field called storageLocation to store information about the storage location of the item.
The constructor of StorageBox takes both the value and the storage location as parameters and calls the superclass constructor using super(value) to set the value.
Here's how you can use this StorageBox class:
As you can see, the StorageBox class can be parameterized with different types (Integer and String in this case), and it inherits the generic type parameter T from its superclass Box<T>.
Generic Method Example: NEW
In this example, Utils is a class with a generic method called getFirstElement. This method takes a List<T> as an argument and returns the first element of the list. Here's how you can use it:
The <T> in Utils.<T>getFirstElement(...) specifies the generic type for the method, and it's inferred based on the type of the list passed as an argument.
These examples demonstrate the use of generic classes and methods in Java, which allow you to create reusable and type-safe components that can work with different data types.
Small use case related example:
In this example, Storage is a generic class that has a type parameter T with an upper bound extends Product. This upper bound constraint specifies that T must be a subclass of (or the same class as) the Product class. Here's how you can use this Storage class:
Nice Must Read Examples
===========================================================================================
Type1: class generic
We can define class which can be vary like this <T>
Eg1:
when the extract implementation relevant class can be provided
Type 3 method generic
Comments
Post a Comment