Programing

정적 메서드 내에서 비 ​​정적 내부 클래스를 인스턴스화하는 방법

crosscheck 2020. 7. 27. 07:33
반응형

정적 메서드 내에서 비 ​​정적 내부 클래스를 인스턴스화하는 방법


다음 코드 조각이 있습니다.

public class MyClass{
   class Inner{
     int s,e,p;
   }

   public static void main(String args[]){
     Inner in;
   }
}

이 부분 개까지의 코드는 괜찮지 만, 내가 좋아하는 main 메소드 내에서 '에'인스턴스화 할 수없는 생각 in=new Inner()이 보여주는 것처럼 non static field cannot be referenced in static context. 내가 할 수있는 방법은 무엇입니까? 내부 클래스를 정적으로 만들고 싶지 않습니다.


다른 외부 클래스에 대한 참조도 있어야합니다.

Inner inner = new MyClass().new Inner();

내부가 정적 인 경우

Inner inner = new MyClass.Inner();

"일반"내부 클래스에는 외부 클래스 인스턴스에 대한 숨겨진 (암시 적) 포인터가 있습니다. 이를 통해 컴파일러는 입력하지 않고도 포인터를 추적하는 코드를 생성 할 수 있습니다. 예를 들어 외부 클래스에 변수 "a"가있는 경우 내부 클래스의 코드는 "a = 0"을 수행 할 수 있지만 컴파일러는 숨겨진 포인터를 유지하면서 "outerPointer.a = 0"에 대한 코드를 생성합니다. 덮개.

이것은 내부 클래스의 인스턴스를 만들 때 연결하려면 외부 클래스의 인스턴스가 있어야 함을 의미합니다. 외부 클래스의 메서드 내에서이 생성을 수행하면 컴파일러는 "this"를 암시 적 포인터로 사용하는 것을 알고 있습니다. 다른 외부 인스턴스에 연결하려면 특별한 "새"구문을 사용하십시오 (아래 코드 스 니펫 참조).

내부 클래스를 "정적"으로 만들면 숨겨진 포인터가 없으며 내부 클래스는 외부 클래스의 멤버를 참조 할 수 없습니다. 정적 내부 클래스는 일반 클래스와 동일하지만 그 이름의 범위는 부모 내부입니다.

다음은 정적 및 비 정적 내부 클래스를 만드는 구문을 보여주는 코드 스 니펫입니다.

public class MyClass {

    int a,b,c; // Some members for MyClass

    static class InnerOne {
        int s,e,p;
        void clearA() {
            //a = 0;  Can't do this ... no outer pointer
        }
    }

    class InnerTwo {
        //MyClass parentPointer;      Hidden pointer to outer instance
        void clearA() {         
            a = 0;
            //outerPointer.a = 0      The compiler generates this code
        }       
    }

    void myClassMember() {
        // The compiler knows that "this" is the outer reference to give
        // to the new "two" instance.
        InnerTwo two = new InnerTwo(); //same as this.new InnerTwo()
    }

    public static void main(String args[]) {

        MyClass outer = new MyClass();

        InnerTwo x = outer.new InnerTwo(); // Have to set the hidden pointer
        InnerOne y = new InnerOne(); // a "static" inner has no hidden pointer
        InnerOne z = new MyClass.InnerOne(); // In other classes you have to spell out the scope

    }

}

new Inner()메소드 내 에서 작성 하려면 클래스의 인스턴스 메소드에서 수행하십시오 MyClass.

public void main(){
  Inner inner = new Inner();
}

public static void main(String args[]){
  new MyClass().main();
}

Alexei Kaigorodov's is the right answer. His solution allows you to instantiate inner classes from within a static method, such as a main() of the same class. Otherwise, you can't instantiate an inner class within a static method. It does not compile. Alexei's solution does compile and it does allow you to instantiate inner classes from a static method. The other answers are interesting side-notes, but I don't find them responsive to the actual question.

import java.awt.Graphics;
import java.awt.Color;
import javax.swing.JPanel;
import javax.swing.JFrame;

public class Example {
    public class InnerClass extends JPanel {
        public void paint(Graphics g) {
            g.setColor(Color.BLACK);
            g.fillRect(getX(),getY(),getWidth(),getHeight());
            g.setColor(Color.RED);
            g.fillRect(5, 20, 195, 20);
            g.setColor(Color.BLACK);
            g.drawString("This was written by an inner class.", 10, 35);
        }
    }

    public void demonstrate() {
        InnerClass sc = new InnerClass();//<---this is key
        JFrame jf = new JFrame();
        jf.add(sc);
        jf.setSize(220, 130);
        jf.setLocation(450, 450);
        jf.show();
    }

    public static void main(String[] params) {
        Example e = new Example();//<---so is this
        e.demonstrate();//<---and this is also key
    }
}

참고URL : https://stackoverflow.com/questions/12690128/how-to-instantiate-non-static-inner-class-within-a-static-method

반응형