: 클래스 내에 또 다른 클래스를 지정할 수 있다.
: 클래스 내 클래스를 중첩 클래스라고 한다
public class 클래스{ // outer 클래스
static int n = 10; // 가능
private int n2 = 10;
int n3 = 10;
class 클래스 { 중첩 클래스 (inner 클래스)
static int n = 10; // 불가능
System.out.println(n2 + n3); // outer 인스턴스변수 사용 가능
}
static class 클래스 {
static int n = 10; // 가능
System.out.println(n2 + n3); // outer의 인스턴스변수 사용 불가
}
}
(1) static 변수 사용 불가 (단, static inner class에서는 사용 가능)
(2) static으로 지정된 중첩클래스는 outer의 인스턴스변수 접근 불가
(3) 반드시 Outer 생성 후 Inner 생성이 가능
=> 직접 Inner 접근이 불가능하고 Outer를 통해 접근 가능. 다른 클래스에서 Inner을 사용하려면 복잡하다
=> 일반적으로 외부클래스에서는 Inner 사용 안 하고 Outer를 사용
(4) 안드로이드 코드에서 많이 쓰임
: outer 클래스의 어떤 위치에 있나?
class Outer {
int n; //멤버변수
public void a() { //멤버메서드
class Inner3 { // ㅣlocal inner class
}
}
class Inner { // member inner class (일반적 중첩 클래스)
}
static class Inner2 {
}
public Outer() {}
}
: 중첩클래스 범주에 속함
: 인터페이스 사용할 때 익명 클래스를 적용할 수 있다
public interface Flyer {
public abstract void fly();
}
// 가. 하위클래스 작성
public class Bird implements Flyer {
@Override
public void fly() {}
// 나. 하위클래스 객체 생성
Bird b = new Bird();
b.fly();
//다형성 적용
Flyer b2 = new Bird();
b2.fly();
}
- 인터페이스명 변수명 = new 인터페이스명() {
// 추상메서드 재정의
};
변수명.메서드();
Flyer f = new Flyer() { // 클래스명이 어디에도 읎다
@Override
public void fly() {} // 추상메서드 재정의
};
f.fly();
: 익명클래스의 축소된 표현
: "기능에만 집중하자" -> 함수형 프로그래밍 (functional programming)
(1) 파라미터 X, 리턴값 X
(2) 파라미터 O, 리턴값 X
(3) 파라미터 X, 리턴값 O
(4) 파라미터 O, 리턴값 O
@FunctionalInterface // 추상메서드를 반드시 1개만 지정하도록 강제
public interface Flyer {
public abstract void fly();
}