Menu
Topics Index
...
`


Generics >
Siva Nookala - 20 Feb 2017
Generic intefaces are specified just like generic classes.

The following program shows how the generic interface works
Generic Interfaces
class TasteDemo
{
    public static void main(String args[])
    {
        
        Taste<Mango> mangoTaste = new Taste<Mango>();
        
        Mango mango = new Mango();
        
        mangoTaste.tellTaste(mango);
        
        Taste<Lemon> lemonTaste = new Taste<Lemon>();
        
        Lemon lemon = new Lemon();
        
        lemonTaste.tellTaste(lemon);
    }
}

interface Fruit<T>

{
    void tellTaste(T fruit);
}
class Taste<T> implements Fruit<T>
{
    public void tellTaste(T fruit)
    {
            
        String fruitName = fruit.getClass().getName();
            
        if(fruitName.equals("Mango"))
        {
            System.out.println("Mango is sweet");
        }
        else if(fruitName.equals("Lemon"))
        {
            System.out.println("Lemon is sour");
        }
    }
    
}
class Mango
{
    
}

class Lemon
{
    
}
OUTPUT

Mango is sweet
Lemon is sour

DESCRIPTION

Generic Interfaces work same as Generic Classes. Here Fruit is a Generic interface and a generic implementation class is Taste.Then the implementation class is used to decide the taste of the fruits: a Mangoand a Lemon.

THINGS TO TRY
  • Create one more class for Orange and print the taste as bitter in Taste class.

0
Wrong
Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.