9_중첩 선언과 익명 객체
9_중첩 선언과 익명 객체
9.1 중첩 클래스
1
2
3
4
5
6
7
8
9
10
11
12
13
class Outer {
class Inner {
void print() {
System.out.println("Inner class");
}
}
}
public class Main {
public static void main(String[] args) {
Outer.Inner inner = new Outer().new Inner();
inner.print();
}
}
- 요약: 중첩 클래스는 클래스 안에 정의된 클래스로, 바깥 클래스와 관련된 기능을 그룹화한다. Encapsulation 을 위해서 사용함 💊 코드 깔끔하게 정리할 수 있음
9.2 인스턴스 멤버 클래스
1
2
3
4
5
6
7
8
9
10
11
12
13
14
class Outer {
class InstanceInner {
void show() {
System.out.println("Instance inner class");
}
}
}
public class Main {
public static void main(String[] args) {
Outer outer = new Outer();
Outer.InstanceInner inner = outer.new InstanceInner();
inner.show();
}
}
- 요약: 인스턴스 멤버 클래스는 바깥 클래스의 인스턴스에 종속된 중첩 클래스다.
9.3 정적 멤버 클래스
1
2
3
4
5
6
7
8
9
10
11
12
13
class Outer {
static class StaticInner {
void display() {
System.out.println("Static inner class");
}
}
}
public class Main {
public static void main(String[] args) {
Outer.StaticInner inner = new Outer.StaticInner();
inner.display();
}
}
- 요약: 정적 멤버 클래스는 바깥 클래스의 인스턴스 없이 독립적으로 생성 가능한 중첩 클래스다.
9.4 로컬 클래스
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Outer {
void method() {
class Local {
void print() {
System.out.println("Local class");
}
}
Local local = new Local();
local.print();
}
}
public class Main {
public static void main(String[] args) {
new Outer().method();
}
}
- 요약: 로컬 클래스는 메서드 내부에 정의되어 해당 메서드에서만 사용되는 클래스다. 함수 실행이 종료되면 가비지 컬렉터가 데려감
9.5 바깥 멤버 접근
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class Outer {
String outerField = "Outer field";
class Inner {
void accessOuter() {
System.out.println(outerField);
}
}
}
public class Main {
public static void main(String[] args) {
Outer outer = new Outer();
Outer.Inner inner = outer.new Inner();
inner.accessOuter();
}
}
- 요약: 중첩 클래스는 바깥 클래스의 멤버에 직접 접근할 수 있다.
9.6 중첩 인터페이스
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Outer {
interface NestedInterface {
void method();
}
class Inner implements NestedInterface {
public void method() {
System.out.println("Nested interface implementation");
}
}
}
public class Main {
public static void main(String[] args) {
Outer.Inner inner = new Outer().new Inner();
inner.method();
}
}
- 요약: 중첩 인터페이스는 클래스 안에 정의된 인터페이스로, 관련 기능을 캡슐화한다.
9.7 익명 객체
1
2
3
4
5
6
7
8
9
10
11
12
13
interface Printable {
void print();
}
public class Main {
public static void main(String[] args) {
Printable p = new Printable() {
public void print() {
System.out.println("Anonymous object");
}
};
p.print();
}
}
- 요약: 익명 객체는 이름 없는 클래스를 즉석에서 정의하고 인스턴스화한 객체다.
This post is licensed under CC BY 4.0 by the author.