🌱 오늘의 주제 : 내부 클래스(inner class)
🌱 내부 클래스(inner class)
- 내부 클래스는 클래스 내에 선언된 클래스이다.
- 클래스에 다른 클래스를 선언한 이유 : 두 클래스 간에 서로 긴밀한 관계에 있기 때문이다.
- 두 클래스의 멤버들 간에 서로 쉽게 접근할 수 있다는 장점
- 코드의 복잡성을 줄일 수 있는 장점. (캡슐화)
🌱 내부 클래스의 종류와 특징
| 내부 클래스 |
특징 |
| 인스턴스 클래스(instance clasds) |
외부클래스의 인스턴스 멤버처럼 다룬다. 주로 외부클래스의 인스턴스 멤버들과 관련된 작업에 사용 |
| 스태틱 클래스(static class) |
외부클래스의 static 멤버처럼 다룬다. 주로 static메서드에서 사용. |
| 지역 클래스(local class) |
선언된 영역 내부에서만 사용 |
| 익명 클래스(anonymous class) |
이름없는 클래스( 일회용) |
package inner_class;
public class Ex7_12 {
class InstanceInner {
int iv = 100;
// static int cv = 100; // static 변수를 선언할 수 없다.
final static int CONST = 100; // final static은 상수이므로 허용
}
static class StaticInner {
int iv = 200;
static int cv = 200; // static 클래스만 static멤버를 정의할 수 있음.
}
void myMethod() {
class LocalInner {
int iv = 300;
// static int cv = 300; // static 변수를 선언할 수 없음.
final static int CONST = 300; // final static은 상수이므로 허용.
}
}
public static void main(String[] args) {
// inner class
System.out.println(InstanceInner.CONST);
System.out.println(StaticInner.cv);
}
}
------------
<결과>
100
200