Monday 10 September 2012

Create multiple objects in Java


Use of Interface in java.

Let's assume we have a Game Class and four subtypes of Game: Hockey, Cricket,Tennis,Football


public static List<Game> getInstances(Class<? extends Game> clazz, int counter)
{
    List games = new ArrayList<Game>();
    for(int i=0;i< counter; i++)
    {
        games.add(clazz.newInstance());
    }
    return games;
}

Now you can use this for creating games.

List<Hockey> hctf = Game.getInstances(Hockey.class,10);
List<Cricket> hctf = Game.getInstances(Cricket.class,10)
List<Tennis> hctf = Game.getInstances(Tennis.class,10)
List<Football> hctf = Game.getInstances(Football.class,10)

No comments:

Post a Comment