Menu
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>();
            
            firstString.set("MeritCampus");
                    
            GenericsType<String> secondString = new GenericsType<String>();
            
            secondString.set("MeritCampus");
                    
            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;
    }
    
}
  
OUTPUT

Are the given two strings equal ? true

DESCRIPTION

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

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

0
Wrong
Score more than 2 points

© meritcampus 2019

All Rights Reserved.

Open In App