Skip to content

Instantly share code, notes, and snippets.

@psamatt
Created February 27, 2017 21:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save psamatt/f79c17eb7fabb0fa81daa9338aafe18a to your computer and use it in GitHub Desktop.
Save psamatt/f79c17eb7fabb0fa81daa9338aafe18a to your computer and use it in GitHub Desktop.
Generics usage
package com.example;
import java.util.HashMap;
final public class AnimalFarm {
private HashMap<String, Animal> animals = new HashMap<>();
public AnimalFarm() {
animals.put("dog", new Dog());
animals.put("cat", new Cat());
}
public <T> T getAnimal(String key, Class<T> type) {
return type.cast(animals.get(key));
}
interface Animal {
String getType();
default void printType() {
System.out.println("I am a " + getType());
}
}
public class Dog implements Animal {
@Override
public String getType() {
return "Dog";
}
}
public class Cat implements Animal {
@Override
public String getType() {
return "Cat";
}
}
}
package com.example;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class AnimalFarmTest {
@Test
public void shouldVerifyAnimals() {
AnimalFarm animalFarm = new AnimalFarm();
AnimalFarm.Cat cat = animalFarm.getAnimal("cat", AnimalFarm.Cat.class);
assertEquals(cat.getType(), "Cat");
assertEquals(animalFarm.getAnimal("dog", AnimalFarm.Dog.class).getType(), "Dog");
cat.printType();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment