<aside>
</aside>
이름 그대로 하나의 클래스 내부에 선언된 클래스이다. 내부에 선언되는 것 외에 다른 쓰임은 일반 클래스와 같다.
코드로 나타내면 다음과 같다.
class Human {
Profile profile;
String home;
static class Profile {
String name;
int age;
}
}
종류로는 인스턴스/스태틱/지역/익명 클래스가 있으며 다른 곳에서 new
를 활용해 내부 클래스의 객체를 선언할 수도 있지만, 내부 클래스는 말그대로 외부 클래스 내부에서 쓰이기 위한 용도가 주 목적임으로 실질적인 내부클래스의 쓰임과 인스턴스가 아닌 스태틱 클래스로 써야하는 이유를 중심으로 공부해볼 것이다.
Human.Profile profile = new Human.Profile();
<aside>
특정 클래스가 하나의 클래스와만 관계를 가질 때, 외부 클래스에 새로 작성하는 것이 아닌 내부 클래스를 작성할 수 있다.
이런 경우 외/내부 클래스를 한 번에 관리하기 수월하며 패키지를 간소화할 수 있다.
public class Human {
private String university;
private Profile profile;
// Human 외부 클래스 생성자
public Human(String name, int age, String university) {
this.profile = new Profile(name, age);
this.university = university;
}
// 내부 클래스
private static class Profile {
String name;
int age;
Profile(String name, int age) {
this.name = name;
this.age = age;
}
}
}
</aside>
<aside>
내부 클래스를 private
로 설정해 클래스를 내부로 숨길 수 있다. 위에서도 외부에서는 Profile
에 접근하지 못하게 하며 캡슐화 효과를 극대화할 수 있다.
// 캡슐화 적용
public class Human {
...
public String getName() {
return this.profile.name;
}
}
// 외부
public class Main {
public static void main(String[] args) {
// 내부클래스 선언 및 캡슐화
Human human = new Human("진", 28, "울산대학교");
System.out.println(human.getName());
}
}
</aside>
<aside>
내부 클래스를 사용하는 것은 외부에 작성하는 경우보다, 물리/논리적으로 외부 클래스에 더 가깝게 위치하게 된다. 따라서 시각적으로 편해질 뿐만 아니라 Profile 클래스가 Human에서만 사용된다면 하나의 클래스에서 코드가 상호작용함으로 유지보수와 코드의 복잡성을 줄일 수 있다.
요약하면, 하나의 클래스에만 연관되는 클래스는 연관관계 생각없이 내부에 선언해 직관적으로 사용할 때 내부 클래스를 사용한다.
</aside>