[Effective Java/아이템24] 멤버 클래스는 되도록 static으로 만들라.
# 아이템24. 멤버 클래스는 되도록 static으로 만들라.
public class StaticCar {
static String _where="I am a Car from Germany!";
Country _country; // object of inner class country
StaticCar(){
_country=new Country(); // instantiate the inner class
}
static class Country { // static member inner class
String showCountry() {
return _where;
}
}
public static void main(String[] args) {
StaticCar myCar= new StaticCar() ; // instantiated object of class StaticCar
System.out.print("Access through an Country reference");
System.out.println(" created in an object of a StaticCar:");
System.out.println(myCar._country.showCountry());
// instantiated object of class StaticCar.Country
StaticCar.Country country= new StaticCar.Country();
System.out.println("Access through an Country reference that is local:");
System.out.println(country.showCountry());
}
}
Access through an Country reference created in an object of a StaticCar:
I am from Germany!
Access through an Country reference that is local:
I am from Germany!
- 정적 멤버 클래스와 비정적 멤버 클래스의 구문상 차이는 단지 static이 붙어있고 없고 뿐이지만, 의미상 차이는 의외로 꽤 크다.
- 비슷하게, Set과 List 같은 다른 컬렉션 인터페이스 구현들도 자신의 반복자를 구현할 때 비정적 멤버 클래스를 주로 사용한다.
public class MySet<E> extends AbstractSet<E> {
... // 생략
@Override public Iterator<E> iterator() {
return new MyIterator();
}
private class MyIterator implements Iterator<E> {
...
}
}
interface Inter {
public void hi();
}
class Anony {
public void f() {
System.out.println("Anony.f() 호출.");
}
}
public class Test {
private Integer number;
public void nonStaticMethod(){
Inter ob2 = new Inter() {
public void hi() {
System.out.println("비 정적문맥 메소드 호출" + number);
}
};
}
public static void staticMethod() {
Inter ob2 = new Inter() {
Integer number2 = 1;
public void hi() {
System.out.println("정적문맥 메소드 호출" + number); // comile Error
}
};
}
public static void main(String[] args) throws Exception {
//Inter ob1 = new Inter(); //Compile Error!!!
Inter ob2 = new Inter() {
public void hi() {
System.out.println("안녕하십니까?");
}
};
ob2.hi();
Anony a1 = new Anony();
Anony a2 = new Anony() {
public void f() {
System.out.println("이히힛.");
}
};
a1.f();
a2.f();
}
}
'dev book > Effective Java' 카테고리의 다른 글
[Effective Java/아이템26] 로타입은 사용하지 마라. (0) | 2022.03.04 |
---|---|
[Effective Java/아이템25] 톱레벨 클래스는 한 파일에 하나만 담아라. (0) | 2022.03.03 |
[Effective Java/아이템23] 태그 달린 클래스보다는 클래스 계층 구조를 활용하라. (0) | 2021.12.10 |
[Effective Java/아이템22] 인터페이스는 타입을 정의하는 용도로만 사용하라. (0) | 2021.12.09 |
[Effective Java/아이템21] 인터페이스는 구현하는 쪽을 생각해 설계하라. (1) | 2021.12.08 |
댓글 개