내부 클래스의 제어자와 접근성
- 내부 클래스의 제어자는 변수에 사용 가능한 제어자와 동일
(private, protected, (default), public)
class Outer {
private int iv = 0;
protected static int cv = 0;
void myMethod() {
int lv = 0;
}
}
class Outer {
private class InstanceInner {}
protected static class StaticInner {}
void myMethod() {
class LocalInner {}
}
}
예제1
class Ex {
class InstanceInner {
int iv = 100;
static int cv = 100;
final static int CONST = 100;
}
static class StaticInner {
int iv = 200;
static int cv = 200;
}
void myMethod() {
class LocalInner {
int iv = 300;
static int cv = 300;
final static int CONST = 300;
}
int i = LocalInner.CONST;
}
public static void main(String args[]) {
System.out.println(InstanceInner.CONST);
System.out.println(StaticInner.cv);
System.out.println(LocalInner.CONST);
}
}
예제2
- static 메서드 : static멤버 접근 가능
- 인스턴스 메서드 : 인스턴스멤버와 static멤버 모두 접근 가능
class Ex {
class InstanceInner {}
static class StaticInner {}
InstanceInner iv = new InstanceInner();
static StaticInner cv = new StaticInner();
static void staticMethod() {
InstanceInner obj1 = new InstanceInner();
StaticInner obj2 = new StaticInner();
}
void instanceMethod() {
InstanceInner obj1 = new InstanceInner();
StaticInner obj2 = new StaticInner();
LocalInner lv = new LocalInner();
}
void myMethod() {
class LocalInner {}
LocalInner lv = new LocalInner();
}
}
예제3
- 내부클래스에서 외부클래스의 private멤버도 접근 가능
- 지역 내부 클래스를 감싸고 있는 메서드의 상수만 사용가능
class Outer {
private int outerIv = 0;
static int outerCv = 0;
class InstanceInner {
int iiv = outerIv;
int iiv2 = outerCv;
}
static class StaticInner {
int siv = outerIv;
static int scv = outerCv;
}
void myMethod() {
final int lv = 0;
final int LV = 0;
class LocalInner {
int iiv = outerIv;
int iiv2 = outerCv;
}
}
}
예제4
class Outer2 {
class InstanceInner {
int iv = 100;
}
static class StaticInner {
int iv = 200;
static int cv = 300;
}
void myMethod() {
class LocalInner {
int iv = 400;
}
}
}
class Ex {
public static void main(String[] args) {
Outer2 oc = new Outer2();
Outer2.InstanceInner ii = oc.new InstanceInner();
System.out.println("ii iv :" + ii.iv);
System.out.println("Outer2.StaticInner.cv :" + Outer2.StaticInner.cv);
Outer2.StaticInner si = new Outer2.StaticInner();
System.out.println("si.iv" + si.iv);
}
}
예제5
class Outer3 {
int value = 10;
class Inner {
int value = 20;
void method1() {
int value = 30;
System.out.println("value :" + value);
System.out.println("this.value :" + this.value);
System.out.println("Outer3.this.value :" + Outer3.this.value);
}
}
}
class Ex {
public static void main(String[] args) {
Outer3 outer = new Outer3();
Outer3.Inner inner = outer.new Inner();
inner.method1();
}
}