7


これがコードです。

public class Test {
        class InnerClass{

               }

   public static void main(String[] args){
            InnerClass ic = new InnerClass();
        }
    }

それはエラーメッセージを言います

non-static variable this cannot be referenced from a static context
after creation of object ic.

誰でも私に理由を教えてもらえますか?

ありがとう

4

3 に答える 3

25

InnerClass needs to be static itself, i.e.

public class Test {

   static class InnerClass{    
   }

   public static void main(String[] args){
      InnerClass ic = new InnerClass();
   }
}

If InnerClass is not static, it can only be instantiated in the context of a parent instance of Test. The rather baroque syntax for this is:

public class Test {

   class InnerClass{    
   }

   public static void main(String[] args){
      Test test = new Test();
      InnerClass ic = test.new InnerClass();
   }
}
于 2011-03-11T12:39:34.060 に答える
2

Your inner class depends on an instance of the Test class. main is a static method, thus you can't create an instance of InnerClass.

I think you want to declare your inner class as static :

class Test {
    static class InnerClass { }

    public static void main(String[] args){
        InnerClass ic = new InnerClass();
    }
}

More information about nested classes : http://download.oracle.com/javase/tutorial/java/javaOO/nested.html

Short explanation

There's mainly two types of nested classes : "static nested class" and "inner class"

Static nested class are used to logically group two classes and can be used to increase encapsulation. They can be used like any other classes and, except for visibility, they don't have any particular access to the outer class fields. They can logically be instantiated in a static context.

Inner class (ie not static) are bound to a particular instance of the outer class. This means you must have an instance of the outer class to instantiate the inner class. Have a look at Skaffman second code chunk for an instantiation example. Since inner classes are bound to an instance of the outer class, they have access to every field relative to this particular instance.

I hope all this is now clearer.

于 2011-03-11T12:40:04.487 に答える
0

まず、「ネストされた」クラスは静的であり、「内部」クラスはそうではありません。

静的クラスは、外側のクラスのすべてのインスタンス間で共有されます (したがって、静的フィールドはすべてのインスタンス間で共有されます)。一方、各インスタンスには非静的内部クラスの独自のバージョンがあります。
非静的内部クラスは、(クラスではなく) 囲んでいるオブジェクトと共に格納され、インスタンスを介してのみアクセスできます。

于 2011-03-11T12:42:50.913 に答える