프로젝트를 진행하면서 RequestDTO 객체와 ResponseDTO 객체를 각각 다른 클래스로 생성하지 않고 DTO라는 한 클래스 내에 static inner class로 각각 생성했다. static inner class에 대해 살짝 공부해봤다.
하나의 클래스 내부에 선언된 또 다른 클래스
문법
class Outer { // 외부 클래스
...
class Inner { // 내부 클래스
...
}
...
}
내부 클래스를 사용하면 다음과 같은 장점이 존재한다.
내부 클래스는 필드와 마찬가지로 선언된 위치에 따라 다음과 같이 구분된다.
외부 클래스 영역에 선언된 클래스 중에서 static 키워드를 가지는 클래스를 정적 클래스(static class)라고 한다.
이러한 정적 클래스는 주로 외부 클래스(outer class)의 클래스 메소드에 사용될 목적으로 선언된다.
public class Outer {
class Inner {
}
}
Outer outer = new Outer();
Outer.Inner inner = new Outer.new Inner();
원래 'inner 혹은 내부'라는 키워드는 static class에 사용하지 않는다고 한다. 단지 차이점을 비교하기 위해서 편의상 사용하며, 정확한 명칭은 static member class (혹은 정적 멤버 클래스) 라고 해야한다.
public class Outer {
static class staticInner {
}
}
Outer.staticInner inner = new Outer.staticInner();
inner static class는 new 연산자를 한번만 사용해도 새로운 인스턴스를 만들 수 있다. 외부 클래스에 대한 인스턴스가 굳이 필요 없다. 따라서 외부참조가 존재하지 않는다.
class MyClass {
void myMethod() {
...
}
class InnerClass{
void innerClassMethod() {
MyClass.this.myMethod(); //숨은 외부 참조가 있기 때문에 가능
}
}
static class InnerStaticClass{
void innerClassMethod() {
MyClass.this.myMethod(); //컴파일 에러
}
}
}
외부 참조가 불가능해도 내부 클래스를 가능한 static으로 선언하라는 이유는 다음과 같다.
inner class를 선언할 때에는 외부 인스턴스 참조가 필요하지 않다면 static 키워드를 붙여준다.
참조
http://www.tcpschool.com/java/java_usingClass_innerClass
https://velog.io/@agugu95/%EC%99%9C-Inner-class%EC%97%90-Static%EC%9D%84-%EB%B6%99%EC%9D%B4%EB%8A%94%EA%B1%B0%EC%A7%80
https://siyoon210.tistory.com/141