Generic Classes in Java

Java Generics was introduced to deal with type-safe objects. It makes the code stable.Java Generics methods and classes, enables programmer with a single method declaration, a set of related methods, a set of related types. Generics also provide compile-time type safety which allows programmers to catch invalid types at compile time. Generic means parameterized types. Using generics, the idea is to allow any data type to be it Integer, String, or any user-defined Datatype and it is possible to create classes that work with different data types.

A Generic class simply means that the items or functions in that class can be generalized with the parameter(example T) to specify that we can add any type as a parameter in place of T like Integer, Character, String, Double or any other user-defined type.

Example

package com.loopandbreak;

class Login<T> {
    private T username;
    private T password;
    public Login(T username, T password) {
        this.username = username;
        this.password = password;
    }

    // Just for printing
    @Override
    public String toString() {
        return "Login{" +
                "username=" + username +
                ", password=" + password +
                '}';
    }
}

public class GenericClasses {
    public static void main(String[] args) {
        Login<Integer> person1 = new Login<>(1, 2);
        Login<String> person2 = new Login<>("canny", "1234");
        System.out.println(person1);
        System.out.println(person2);
    }
}

Output

Login{username=1, password=2}
Login{username=canny, password=1234}
Share

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *