728x90
중첩클래스와 중첩인터페이스
class ClassName {
class NestedClassName {
}
}
class ClassName {
interface NestedInterfaceName{
}
}
중첩클래스
중첩클래스 예제
//바깥클래스
class A {
A(){System.out.println("A 객체가 생성됨");}
//인스턴스멤버클래스
class B {
B(){System.out.println("B 객체가 생성됨");}
int field1;
//static int field2;불가
void method1(){
System.out.println(field1);
}
//static void method2(){}불가
}
//정적멤버클래스
static class C{
C(){System.out.println("C 객체가 생성됨");}
int field1;
static int field2;
void method1(){
System.out.println(field1);
System.out.println(field2);
}
static void method2(){
// System.out.println(field1); 불가
System.out.println(field2);
}
}
void method(){
//로컬클래스
class D{
D(){System.out.println("D 객체가 생성됨");}
int field1;
//static int field2; 불가
void method(){
System.out.println(field1);
}
//static void method(){} 불가
}
D d = new D();
d.field1 = 3;
d.method();
}
}
public class Main {
public static void main(String[] args) {
A a = new A();
//인스턴스 멤버 클래스 객체 생성
A.B b = a.new B();
b.field1 = 3;
b.method1();
//정적 멤버 클래스 객체 생성
A.C c = new A.C();
c.field1 = 3;
c.method1();
A.C.field2 = 3;
A.C.method2();
//로컬 클래스 객체 생성을 위한 메소드 호출
a.method();
}
}
중첩클래스의 this()
public class OutterEx {
public static void main(String[] args){
Outter outter = new Outter();
Outter.Nested nested = outter.new Nested();
nested.print();
}
}
public class Outter {
String field = "Outter-field";
void method(){
System.out.println("Outter-method");
}
class Nested{
String field = "Nested-field";
void method(){
System.out.println("Nested-method");
}
void print(){
System.out.println("첫번째 this.field :"+this.field);
System.out.println("두번째 this.method() 실행");
this.method();
System.out.println("세번째 Outter.this.field :"+Outter.this.field);
System.out.println("네번째 Outter.this.method() 실행");
Outter.this.method();
}
}
}
중첩인터페이스
package ex3_interface;
public class Button {
OnClickListener listener;
void setOnClickListener(OnClickListener listener){
this.listener = listener;
}
void touch() {
listener.onClick();
}
interface OnClickListener{
void onClick();
}
}
package ex3_interface;
public class MessageListener implements Button.OnClickListener{
@Override
public void onClick() {
System.out.println("메세지를 보냅니다.");
}
}
package ex3_interface;
public class CallListener implements Button.OnClickListener{
@Override
public void onClick() {
System.out.println("전화를 겁니다");
}
}
package ex3_interface;
public class ButtonExample {
public static void main(String[] args) {
Button btn = new Button();
btn.setOnClickListener(new CallListener());
btn.touch();
btn.setOnClickListener(new MessageListener());
btn.touch();
}
}
이미지 출처 : 이것이자바다
728x90
'STUDY > JAVA' 카테고리의 다른 글
[JAVA] 22-07-18 익명 객체 ☑ (0) | 2022.07.18 |
---|---|
[JAVA] 22-06-13 상수풀 / String · StringBuilder · StringBuffer ☑ (0) | 2022.07.18 |
[JAVA-이것이자바다.6장] 클래스 확인 문제 (0) | 2022.07.13 |
[JAVA-이것이자바다.5장] 참조 타입 확인 문제 (0) | 2022.07.13 |
[JAVA] 22-07-08 인터페이스를 이용한 주행 모드 바꾸기 문제 ☑ (0) | 2022.07.10 |