Skip to content

abhinav-nath/java-generics

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

12 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Generics

Generics enable types to be parameters when defining classes and methods and with that you can re-use the same code with different inputs (types).

This class can store a String, an Integer or any Custom object. The purpose of this Box is to re-use it for any kind of data.

public class Box<T> {
    private T type;

    public void set(T type) {
        this.type = type;
    }

    public T get() {
        return type;
    }

    // T is a type parameter
}
Box<String> favoriteColor = new Box<>();
favoriteColor.set("BLACK");
favoriteColor.set(10); // compilation error
Box<Integer> favoriteNumber = new Box<>();
favoriteNumber.set(27);
Box<Animal> favoriteAnimal = new Box<>();
favoriteAnimal.set("Tiger");


⭐ Star this repository — it helps!

Releases

No releases published

Packages

No packages published

Languages