본문 바로가기
Programming/Java

Troubleshoot #1 No enclosing instance of type ... is accessible

by jaegom 2020. 6. 11.

생성하는 자바 파일의 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되어있지 않기 때문에 동일 패키지에서 같은 이름으로 클래스 생성도 불가능합니다.

댓글