Created
February 27, 2017 21:57
-
-
Save psamatt/f79c17eb7fabb0fa81daa9338aafe18a to your computer and use it in GitHub Desktop.
Generics usage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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