Topics Index

Generics >
Siva Nookala - 06 Oct 2016
Sometimes we do not want whole class to be parameterized, in that case we can use generics type in methods also. Since constructor is a special kind of method, we can use generics type in constructors too.

The following program showing example of generics type in method.
Generics in Methods and Constructors
class GenericsTypesInMethod
        public static <T> boolean areEqual(GenericsType<T> t1, GenericsType<T> t2)
            return t1.get().equals(t2.get());
        public static void main(String args[])
            GenericsType<String> firstString = new GenericsType<String>();
            GenericsType<String> secondString = new GenericsType<String>();
            boolean areEqual;
            areEqual = GenericsTypesInMethod.areEqual(firstString, secondString); // LINE A
            System.out.println("Are the given two strings equal ? " +areEqual );

class GenericsType<T>
    private T object;
    public T get()
        return this.object;
    public void set(T object)
        this.object = object;

Are the given two strings equal ? true


Here, notice the areEqualmethod signature showing syntax to use generics type in methods.

  • Replace code at LINE A with areEqual = GenericsTypesInMethod.<String>areEqual(firstString, secondString); run the program and see it also gives same result.

Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App