![]() |
VOOZH | about |
Generics allow classes, interfaces and methods to operate on objects of various types while ensuring type safety. Type parameters are specified in angle brackets (<>) and enable code reusability without sacrificing type checks at compile time.
Generic constructors define their type parameter before the constructor name, even if the class itself is not generic. It can accept arguments of any type and is mainly used to create flexible and type-safe object initialization.
Implementation:
Number to Double Conversion: v: 10.0 v: 136.8000030517578
Explanation:
Generic interfaces define abstract data types that operate on various object types while ensuring type safety. They support multiple inheritance, contain only abstract methods and constants and use the implements keyword. Like generic classes, they enable code reusability but cannot be instantiated directly.
The benefits of Generic Interface are as follows:
Syntax:
interface interface-Name < type-parameter-list > {
//....
} class class-name <type-parameter-list> implements interface-name <type-arguments-list> {
//...
}
Implementation: The following example creates an interface 'MinMax' which involves very basic methods such as min(), max() just in order to illustrate as they return the minimum and maximum values of given objects.
Example
Minimum value: 2 Maximum value: 8
Explanation:
Note: Once a bound is established, it is not necessary to state it again in implements clause. If a class implements generic interface, then class must be generic so that it takes a type parameter passed to interface.