我有以下的代码:
public class MyClass{
class Inner{
int s,e,p;
}
public static void main(String args[]){
Inner in;
}
}
高达这部分代码是好的,但我不能够的主要方法中“IN”实例化等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”保持隐藏的指针代码盖。
这意味着当你创建你必须有一个外部类的实例来链接到一个内部类的一个实例。 如果你做的外部类的方法,这里面创造那么编译器知道使用“这个”作为隐含的指针。 如果你要链接到其他一些外实例,然后你使用一个特殊的“新”的语法(见下面的代码片段)。
如果你让你的内部类“静态”那么有没有隐藏的指针和您的内部类不能引用外部类的成员。 静态内部类是相同的规则的类,但是它的名字的作用域确定父内部。
这里是一个演示了创建静态和非静态内部类的语法的代码片段:
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();
}
阿列克谢·凯戈罗多瓦的是正确的答案。 他的解决方案允许初始化从一个静态方法中的内部类,诸如主()同一类的。 否则,你不能静态方法中实例化一个内部类。 它不编译。 阿列克谢的解决方案并编译和它允许你从一个静态方法实例化内部类。 其他答案很有意思边笔记,但我不认为他们响应的实际问题。
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
}
}