--Technique that allows you to define classes and methods without fixing the data type --Generics methods can be replaced by overloading. However, overloading is smart because you have to define multiple methods, but using generics you only have to define one method.
Sample.java
//Class using generics
class Hello<T> {
	T data1;
	
	//constructor
	public Hello(T data) {
		this.data1 = data;
	}
	//Method
	public T getData1() {
		return data1;
	}
}
//Calling class
public class Sample {
	public static void main(String[] args) {
		//String type
		Hello<String> s1 = new Hello<>("String");
		System.out.println(s1.getData1());
		//Integer type
		Hello<Integer> s2 = new Hello<>(100);
		System.out.println(s2.getData1());
		
	}
}
javac Sample.java
java Sample
String
100
        Recommended Posts