[Java] Generics sample

What is Generics?

--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

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());
		
	}
}

I'll call you

javac Sample.java
java Sample

Execution result

String
100

Recommended Posts

[Java] Generics sample
[Java] Generics
Java Generics Summary
Java Generics (Notes)
Java sample code 02
Java sample code 03
Selenium sample (Java)
Java GUI sample
Java sample code 04
Java sample code 01
[Java] Holiday judgment sample
Frequently used Java generics
[Java] logback slf4j sample
Digital signature sample code (JAVA)
Java parallelization code sample collection
[Java] Generics classes and generics methods
Java
Java standard log output sample
java Generics T and? Difference
Java
Selenium Sample Reservation Form (Java)
Java 9 new features and sample code
Effective Java 3rd Edition Chapter 5 Generics
A simple sample callback in Java
[Java] Try to implement using generics
Java generics (defines classes and methods)
BloomFilter description and implementation sample (JAVA)
[Java] Date period duplication check sample
EXCEL file update sample with JAVA
Generics of Kotlin for Java developers
Sample vending machine made in Java
Sample code using Minio from Java
Java learning (0)
Studying Java ―― 3
[Java] array
Java protected
[Java] Annotation
[Java] Module
Java array
Studying Java ―― 9
Java scratch scratch
Java tips, tips
Java methods
Java method
java (constructor)
Java array
java (override)
java (method)
Java Day 2018
Java string
Java static
Java serialization
java beginner 4
JAVA paid
Studying Java ―― 4
Java (set)
java shellsort
[Java] compareTo
Studying Java -5
java reflexes
java (interface)