Generics allows parameters to be parameters Generics allows you to define types (classes and interfaces) as parameters when defining classes, interfaces, and methods. This is similar to the familiar formal parameters used in method declarations. The difference is that the inputs for formal parameters are values, and the inputs for type parameters are types. Example below: Using a formalized parameterized method and generics: -
class Room { private Object object; public void add(Object object) { this.object = object; } public Object get() { return object; } } public class Main { public static void main(String[] args) { Room room = new Room(); room.add(60);
General version version: -
class Room<T> { private T t; public void add(T t) { this.t = t; } public T get() { return t; } } public class Main { public static void main(String[] args) { Room<Integer> room = new Room<Integer>(); room.add(60); Integer i = room.get(); System.out.println(i); } }
In the brilliant version of the class, if someone adds room.add("60") , a compile-time error will be shown.
source 1.Info 2. Example from
source share