Notice
Recent Posts
Recent Comments
Link
01-17 05:31
꿈 많은 사람의 이야기
자바 중첩 인터페이스, 익명 인터페이스(익명 객체) 본문
반응형
중첩 인터페이스는 클래스의 멤버로 선언된 인터페이스를 말한다. 인터페이스를 클래스 내부에 선언하는 이유는 해당 클래스와 긴밀한 관계를 맺는 구현 클래스를 만들기 위해서이다.
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 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 | package Study_myself_3_from_390; class Button2 { OnClickLisnter listner; void setOnClickListener(OnClickLisnter listener) { this.listner = listener; } void touch() { listner.onClick(); } interface OnClickLisnter{ void onClick(); } } class CallListener implements Button2.OnClickLisnter{ public void onClick() { System.out.println("전화를 겁니다."); } } class MessageListener implements Button2.OnClickLisnter //인터페이스를 구현 { public void onClick() { System.out.println("메시지를 보냅니다."); } } public class Button { public static void main(String[] args) { Button2 btn = new Button2(); btn.setOnClickListener(new CallListener()); //내부 인터페이스 객체 생성 -> CallListener클래스 형식으로 생성 btn.touch(); btn.setOnClickListener(new MessageListener()); //내부 인터페이스 객체 생성 -> MessageListener클래스 형식으로 생성 btn.touch(); } } Colored by Color Scripter |
위 예제를 보면 Button 클래스 내부에 인터페이스가 존재한다. Message클래스와 Call 클래스는 해당 Button클래스 내부에 있는 인터페이스를 구현한다. 그래서 onClick()이라는 메소드가 오버라이딩 되어있다.
메인에서 Button클래스의 객체를 생성하고 setOnClickListener( ) 메소드를 호출할 때 해당 인터페이스를 구현하는 자식 클래스로 값을 넘겨 준다. 그러면 다형성의 효과로 onClick( ) 메소드가 각 자식이 오버라이딩한 결과가 나오게 된다.
이런식으로 해당 클래스와 밀접한 관계를 갖는 클래스를 만들 때 중첩 인터페이스를 만든다.
익명 객체는 이름이 없는 객체를 말한다. 익명 객체는 단독으로 생성할 수 없고 클래스를 상속하거나 인터페이스를 구현해야만 생성할 수 있다.
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 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 | public class Person { void wake() { System.out.println("7시에 일어납니다."); } } public class Anonymous { Person field = new Person(){ void work() { System.out.println("출근합니다."); } void wake() { System.out.println("6시에 일어납니다."); } }; void method1() { Person localVar = new Person(){ void walk() { System.out.println("산책합니다."); } void wake() { System.out.println("7시30분에 일어납니다."); } }; localVar.wake(); //외부에서 method1을 호출하면 얘가 실행됨 } void method2(Person person) { person.wake(); } } public class AnonymousExample { public static void main(String[] args) { Anonymous a = new Anonymous(); a.field.wake(); a.method1(); } } Colored by Color Scripter |
익명 객체를 생성하는 것은 위 예제와 같다.
반응형
'java' 카테고리의 다른 글
자바 예외 처리(try catch), throws, throw, 사용자 정의 예외 클래스 (0) | 2017.08.17 |
---|---|
자바 예외처리(try catch) (0) | 2017.08.17 |
자바 중첩 인터페이스, 익명 인터페이스(익명 객체) (0) | 2017.08.17 |
중첩 클래스, 내부 클래스(inner class, nested class), 로컬 클래스 (0) | 2017.08.16 |
자바 인터페이스 - 2 (0) | 2017.08.16 |
자바 인터페이스 - 1 (0) | 2017.08.16 |
0 Comments