본문 바로가기
java

[java] No enclosing instance of type xxx is accessible 에러

by hong0 2021. 8. 9.
반응형

하위 클래스에서 상위 클래스가 생성되기 전에 사용하려고 할때 발생하는 에러이다.

 

아래와 같은 class가 있다고 하자.

public class parent {
	
    String str;
    
    public class child {
    	int a;
        int b;
        int c;
    }
}

 

아래와 같이 child class를 생성할 경우 아래와 같은 error가 발생한다.

No enclosing instance of type parent is accessible. Must qualify the allocation with an enclosing instance of type parent (e.g. x.new A() where is an instance of parent).

public class test {

	public static void main(String[] args) {
    	child class_child = new child(); // error
    }
}

 

해결방법은 child class를 parent의 하위 class로 선언하지 않고 접근하거나, 정적 class로 선언하여 생성하는 방법이 있을 수 있다. 그러나 현재 상태를 유지하면서 접근하는 방법은 아래와 같다.

public class test {

	public static void main(String[] args) {
    	parent class_parent = new parent();
        parent.child class_child = class_parent.new child();
    }
}

 

 

반응형

댓글