Java/Java Training
[Java] 네릭 클래스를 이용한 연습
군우
2018. 3. 12. 15:03
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 | package generic21; public class PersonMain { public static void main(String[] args){ PersonProcess<PersonKind> kind = new PersonProcess<PersonKind>(); kind.storeName(new PersonKind()); // 연결시키는 형태 PersonProcess<PersonBad> bad = new PersonProcess<PersonBad>(); bad.storeName(new PersonBad()); showThing(kind); showThing(bad); inputScore(kind, 90); inputScore(bad, 10); showThing(kind); showThing(bad); } public static void inputScore(PersonProcess <? extends Person> box, int a) { Person person = box.inputName() ; person.storeScore(a); } public static void showThing(PersonProcess <? extends Person> box) { Person person = box.inputName() ; person.showThing(); } } | cs |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | package generic21; public class PersonProcess <T> { T kindness; public void storeName(T kindness) { this.kindness = kindness; } public T inputName() // 저장한 연결 반환 { return kindness; } } | cs |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | package generic21; public class Person { int score; public void showThing() { System.out.println("Person"); } public void storeScore(int score) { // TODO Auto-generated method stub this.score = score; } } | cs |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | package generic21; public class PersonKind extends Person { int score; public void showThing() { System.out.println("Kind Person"); System.out.println("점수 : "+ score+"\n"); } public void storeScore(int score) { // TODO Auto-generated method stub this.score = score; } } | cs |
1 2 3 4 5 6 7 8 9 10 11 12 13 | package generic21; public class PersonBad extends Person{ int score; public void showThing() { System.out.println("Bad Person"); System.out.println("점수 : "+ score+"\n"); } public void storeScore(int score) { this.score = score; } } | cs |
PersonMain에서 제네릭을 이용해서 PersonProcess에 접근한다
그때 제네릭을 이용해서
PersonProcess<PersonKind> kind = new PersonProcess<PersonKind>();
이렇게 Kind에한정할 수 있게한다.
그 후 Personprocess에 kind 한정이라는 것을 저장한다.