Showing posts with label generics. Show all posts
Showing posts with label generics. Show all posts

Thursday, June 27, 2013

Definiing method level Generics

How to define Generics at method level:

public class MethodLevelGenericTest {

    public static void main(String[] args) {
        Actor actor = new Actor();
        actor.setName("Arnold");
       
        Dancer dancer = new Dancer();
        dancer.setName("MJ");
       
        Singer singer = new Singer();
        singer.setName("JLo");
       
        System.out.println(actor.getName());
        System.out.println(dancer.getName());
        System.out.println(singer.getName());
    }
   
    // Magical method with Generics!
    public static <person extends Person> String getName(person p) {
        return p.getName();
    }
}

This prints:
Arnold
MJ
JLo

public class Actor extends Person {
    private String profession;

    public String getProfession() {
        return profession;
    }
    public void setProfession(String profession) {
        this.profession = profession;
    }
}

public class Dancer extends Person {
    private String profession;

    public String getProfession() {
        return profession;
    }
    public void setProfession(String profession) {
        this.profession = profession;
    }
}

public class Singer extends Person {
    private String profession;

    public String getProfession() {
        return profession;
    }
    public void setProfession(String profession) {
        this.profession = profession;
    }

}


The other scenario of Bounded Wildcards is explained well in below article:
http://code.scottshipp.com/2013/07/23/collections-of-objects-of-different-types-and-the-bounded-wildcard/