programing

GeoLocation 유형의 폐쇄 인스턴스를 사용하여 할당을 한정해야 합니다.

sourcetip 2022. 10. 18. 22:28
반응형

GeoLocation 유형의 폐쇄 인스턴스를 사용하여 할당을 한정해야 합니다.

이 에러는...

GeoLocation 유형의 폐쇄 인스턴스에 액세스할 수 없습니다. GeoLocation 유형의 둘러싸인 인스턴스(예: x.new A()로 할당 수식을 수행해야 합니다. 여기서 x는 GeoLocation의 인스턴스입니다.이 오류는 새로운 스레드 태스크(i)에서 발생합니다.왜 이런 일이 생기는지 모르겠어요.어떤 제안이라도 감사히 받겠습니다.

public class GeoLocation {
    public static void main(String[] args) throws InterruptedException {
        int size = 10;

        // create thread pool with given size
        ExecutorService service = Executors.newFixedThreadPool(size); 

        // queue some tasks
        for(int i = 0; i < 3 * size; i++) {
            service.submit(new ThreadTask(i));
        }

        // wait for termination        
        service.shutdown();
        service.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS); 
    }

    class ThreadTask implements Runnable {
        private int id;

        public ThreadTask(int id) {
            this.id = id;
        }

        public void run() {
            System.out.println("I am task " + id);
        }
    }

}

이 오류는 내부 클래스의 인스턴스를 생성하려고 하기 때문에 발생합니다.service.submit(new ThreadTask(i));기본 클래스의 인스턴스를 만들지 않고..

이 문제를 해결하려면 먼저 주 클래스의 인스턴스를 생성하십시오.

GeoLocation outer = new GeoLocation();

그런 다음 호출하려는 클래스의 인스턴스를 다음과 같이 만듭니다.

service.submit(outer.new ThreadTask(i));

다른 옵션으로는 내부 클래스를 스태틱하게 설정하는 것이 좋습니다.

public static class ThreadTask implements Runnable { ... }

인라인 클래스 만들기static.

public class OuterClass {

    static class InnerClass {
    }

    public InnerClass instance = new OuterClass.InnerClass();
}

그런 다음 다음과 같이 내부 클래스를 인스턴스화할 수 있습니다.

new OuterClass.InnerClass();

다음 구조 실행:

파일GeoLocation.java

public class GeoLocation {

    public static void main(String[] args) throws InterruptedException {

        int size = 10;

        // create thread pool with given size
        ExecutorService service = Executors.newFixedThreadPool(size); 

        // queue some tasks
        for(int i = 0; i < 3 * size; i++) {
            service.submit(new ThreadTask(i));
        }

        // wait for termination        
        service.shutdown();
        service.awaitTermination(Long.MAX_VALUE, TimeUnit.DAYS); 
    }

}

파일ThreadTask.java

public class ThreadTask implements Runnable {
    private int id;

    public ThreadTask(int id) {
        this.id = id;
    }

    public void run() {
        System.out.println("I am task " + id);
    }
}

내부 클래스의 인스턴스를 만들려면 부모 클래스의 인스턴스를 만들어야 합니다.다음은 예를 제시하겠습니다.

package RandomTests;

public class FinalConstructorTest {


    public static void main (String [] arg){
        FinalConstructorTest fct= new FinalConstructorTest();
        InnerClass1 f1= fct.new InnerClass1(99);
        InnerClass2 f2= fct.new InnerClass2();
    }

    class InnerClass1{
        private final int num2;

        protected InnerClass1(int num){
            num2= num;
            System.out.println("num2= "+ num2);
        }
    }
    class InnerClass2{
        //private static final int x; //Doesn't work
        private final int y; 

        {
            y= 5;
            System.out.println("y= "+ y);
        }
    }
}

스태틱 메서드 등에서 비 스태틱멤버에 액세스 하고 있는 경우에도 이 문제가 발생할 수 있습니다.다음으로 에러의 원인이 되는 2가지 측면과 해결된 코드의 다른 부분을 나타냅니다.다른 사람을 '정적'으로 만드는 것이 문제일 뿐이다.

package Stack;

import java.util.Stack;
import java.util.*;

public class StackArrList {

    public static void main(String[] args) {


        Scanner in = new Scanner(System.in);

        Stack S = new Stack();
        System.out.println("Enter some integers and keep 0 at last:\n");
        int n = in.nextInt();

        while (n != 0) {
            S.push(n);
            n = in.nextInt();
        }
        System.out.println("Numbers in reverse order:\n");

        while (!S.empty()) {

            System.out.printf("%d", S.pop());
            System.out.println("\n");

        }

    }

    public class Stack {
        final static int MaxStack = 100;
        final static int Value = -999999;
        int top = -1;
        int[] ST = new int[MaxStack];

        public boolean empty() {
            return top == -1;
        }

        public int pop() {

            if (this.empty()) {
                return Value;
            }
            int hold = ST[top];
            top--;
            return hold;
        }

        public void push(int n) {
            if (top == MaxStack - 1) {
                System.out.println("\n Stack Overflow\n");
                System.exit(1);
            }
            top++;
            ST[top] = n;

        }

    }

}

이로 인해 StackArList 유형의 엔클로징인스턴스가 액세스 할 수 없습니다.라는 오류가 발생합니다. StackArrList 유형의 둘러싸인 인스턴스(예를 들어 x.new A()에서 x는 StackArList의 인스턴스)를 사용하여 할당을 한정해야 합니다.스택 클래스의 인스턴스를 만들 수 없습니다.

Stack to static class를 만들면 Stack to static class는 정상적으로 동작하며 오류는 발생하지 않습니다.

package Stack;

import java.util.Stack;
import java.util.*;

public class StackArrList {

    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);

        Stack S = new Stack();
        System.out.println("Enter some integers and keep 0 at last:\n");
        int n = in.nextInt();

        while (n != 0) {
            S.push(n);
            n = in.nextInt();
        }
        System.out.println("Numbers in reverse order:\n");

        while (!S.empty()) {

            System.out.printf("%d", S.pop());
            System.out.println("\n");

        }

    }

    static class Stack {
        final static int MaxStack = 100;
        final static int Value = -999999;
        int top = -1;
        int[] ST = new int[MaxStack];

        public boolean empty() {
            return top == -1;
        }

        public int pop() {

            if (this.empty()) {
                return Value;
            }
            int hold = ST[top];
            top--;
            return hold;
        }

        public void push(int n) {
            if (top == MaxStack - 1) {
                System.out.println("\n Stack Overflow\n");
                System.exit(1);
            }
            top++;
            ST[top] = n;

        }

    }

}

언급URL : https://stackoverflow.com/questions/9744639/must-qualify-the-allocation-with-an-enclosing-instance-of-type-geolocation

반응형