1. static nested class
하나의 관심사에 해당하는 내용을 하나의 단위로 묶기 위해 사용
당연히 내부 클래스에 접근 가능.
public class StaticNested {
static class Nest {
public void n() {
System.out.println("static");
}
}
public static void main(String[] args) {
// 외부 클래스를 컴파일하면 내부 스태틱 클래스도 자동으로 컴파일된다.
// 접근 방법.
StaticNested.Nest nest = new StaticNested.Nest();
nest.n();
}
}
2. inner class
내부 구현을 감추고 싶을 때
당연히 내부 클래스에 접근 불가능.
(1) local inner class(내부클래스)
public class Inner {
private class LocalInner {
private int data;
public int getData() {
return data;
}
public void setData(int data) {
this.data = data;
}
}
public static void main(String[] args) {
// static nested class와 다르게 생성자를 각각 만들어줘야한다.
Inner inner = new Inner();
Inner.LocalInner localInner = inner.new LocalInner();
System.out.println(localInner.getData());
}
}
내부 클래스에 접근하는 방법이고, 같은 클래스 내에 있기 때문에 에러가 발생하지 않는다.
이렇게 클래스 안에 있는 내용을 외부에 공개하고 싶지 않을 때 사용한다.
(2) anonymous class(익명클래스)
클래스를 직접 만들어서 사용하고 싶지 않을 때
PriorityQueue<Integer> pq = new PriorityQueue<>(new Comparator<Integer>() {
@Override
public int compare(Integer o1, Integer o2) {
return 0;
}
});
'JAVA' 카테고리의 다른 글
nested class(중첩 클래스) (0) | 2022.04.23 |
---|---|
절차지향과 객체지향의 차이점 (0) | 2022.04.23 |
상속 (0) | 2022.04.20 |
interface와 abstract 차이점 (0) | 2022.04.20 |
java generic (0) | 2021.12.17 |