생성하는 자바 파일의 public class 이름을 Foo라고 합시다.
여러 클래스를 혼용하여 사용할 시 발생하는 에러가 있습니다.
No enclosing instance of type Foo is accessible. Must qualify the allocation with an enclosing instance of type Foo (e.g. x.new A() where x is an instance of Foo).
발생하는 예시입니다.
import java.util.*;
public class Foo {
public static void main(String[] args) {
tester t = new tester(); //위의 에러 발생
}
class tester { //빈 클래스 }
}
발생 이유는 non-static 클래스 tester의 객체 t를 static 메소드인 main 메소드에서 생성하려고 하였기 때문입니다.
non-static 클래스인 tester는 컴파일 시 생성이 되는데 컴파일 전에 사용하려니 당연히 t의 소속이 없는 것입니다.
수많은 블로그에서 tester에 static 속성을 넣는게 해결책이라고 하지만 해결책은 여러가지입니다.
1. 클래스에 static 속성 부여
import java.util.*;
public class Foo {
public static void main(String[] args) {
tester t = new tester();
}
static class tester { //빈 클래스 }
}
에러는 해결이 되지만 static 남발은 static 영역에 클래스를 계속 상주시키므로 메모리 관리 차원에서 다시 생각해봐야 할 것 같습니다.
2. main의 static 속성 제거
import java.util.*;
public class Foo {
public void main(String[] args) {
tester t = new tester();
}
class tester { //빈 클래스 }
}
가능은 하지만.. main 함수를 건드리는 것은 별로 좋아보이진 않네요.
3. 객체 생성을 main 함수 밖에서 하기
import java.util.*;
public class Foo {
tester t = new tester();
public static void main(String[] args) {
}
class tester { //빈 클래스 }
}
4. Tester 클래스를 Top level 클래스로 빼기
import java.util.*;
public class Foo {
public void main(String[] args) {
tester t = new tester();
}
}
class tester { //빈 클래스 }
Top level 클래스로 tester를 선언하는 방법입니다.
이렇게 생성할 경우 tester클래스를 public class로 선언이 불가능하여 다른 파일에서 접근이 불가능합니다
(1 파일 1 public class).
또한 Foo에 nested되어있지 않기 때문에 동일 패키지에서 같은 이름으로 클래스 생성도 불가능합니다.
'Programming > Java' 카테고리의 다른 글
5장. 상속 #4 추상 메소드/클래스 (0) | 2020.06.13 |
---|---|
5장. 상속 #3 오버라이딩 (0) | 2020.06.12 |
5장. 상속 #2 업/다운캐스팅 (0) | 2020.06.11 |
5장. 상속 #1 슈퍼/서브클래스 (0) | 2020.06.11 |
4장. 클래스와 객체 #5 접근지정자 #6 static과 non-static (0) | 2020.06.10 |
댓글