ArrayList<String> arrList = new ArrayList<>(); 라고 하면, 이제 arrList에는 String 자료형만 들어올 수 있다.class Coffee{
void makeCoffee(){}
}
class Soda{
void makeSoda(){}
}
class A<T>{
private T ingrement;
public T getIngrement(){return ingrement;}
public void setIngrement(T ingrement){this.ingrement = ingrement;}
}
public class Main{
public static void main(String[] args){
A<Coffee> a = new A<Coffee>();
a.setIngrement(new Coffee);
a.getIngrement().makeCoffee();
}
}
A<Coffee> a = new A<Coffee>(); 여기서 뒤에 Coffee는 생략 가능하다.A<Coffee> a = new A<>();<T>에 제한을 둘 수 있다. <T> -> <T extends 부모클래스>로 해주면 된다.abstract class Parent{
public abstract void makeDrink();
}
class Coffee extends Parent{
public void makeDrink(){System.out.println("Coffee");}
}
class Soda extends Parent{
public void makeDrink(){System.out.println("Soda");}
}
class Milk{
public void makeDrink(){System.out.println("Milk");}
}
class A<T extends Parent>{
private T ingrement;
public T getIngrement(){return ingrement;}
public void setIngrement(T ingrement){this.ingrement = ingrement;}
}
public class Main{
public static void main(String[] args){
A<Coffee> a = new A<Coffee>();
a.setIngrement(new Coffee);
a.getIngrement().makeCoffee();
}
}이렇게 extends로 제한을 둔다. class Coke{
public void ttt(){
System.out.println("Coke 출력");
}
}
class 음료자판기<T extends Coke>{
public void tmp(T t){
t.ttt();
}
}
public class Main {
public static void main(String[] args) {
음료자판기<Coke> c = new 음료자판기<>();
c.tmp(new Coke());
}
}
여기서 class 음료자판기<T>{} T만 받아서 t.ttt()하면 오류난다. 음료자판기 class 내에서는 누구의 ttt()를 실행해야 하는지 모르기 때문에 오류가 난다.
밑에 Main에서 음료자판기<Coke>로 인스턴스생성을 하는 것은 Main에서 Coke관련해서 음료자판기를 사용한다는 뜻이지 직관적으로 대입한다는 뜻은 아니다.
((Coke)t).ttt();<T extends Coke 혹은 Coke부모>