2016-08-09 23 views
2

私は内部クラスに新しく、これは非常にばかげた質問かもしれませんが、 "外部クラスのインスタンスなしで内部クラスのインスタンスを作成することはできません"私は私の非外部のクラスのインスタンスメンバーとしてそれを使用して私の非静的な内部クラスのオブジェクトを作成しようとしました。外部クラス参照を参照しない非静的内部クラスオブジェクトの作成

私は外側のクラスオブジェクトへの参照によって内側のオブジェクトを作成していますが、それは正しい方法ですか?以下は

は私のコードスニペットです:

public class TestInner { 

    private Nonstatic non = null; 
    private static int access = 4; 

    public class Nonstatic 
    { 
     void hello(){ 
      access = 90; 

     } 
    } 
    public static void main(String[] args) { 
     // TODO Auto-generated method stub 


     TestInner outer = new TestInner(); 
     TestInner.Nonstatic innern= outer.new Nonstatic(); 
     System.out.println("Non static obj1 is "+innern); 

     outer.testinnerObj(); 

    } 


    public void testinnerObj() 
    { 
     non = new Nonstatic(); 
     System.out.println("Non static obj2 is "+non); 
     non.hello(); 

    } 

} 
+0

https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html –

答えて

1

あなたが書いている「内部クラスのインスタンスは、外側のクラスのインスタンスなしで作成することができません」。それはまさにあなたがやっていることです。

まず、あなたは「外側」クラスのインスタンスを作成します。

TestInner outer = new TestInner(); 

その後、あなたは「内側」クラスのインスタンスを作成する - それが唯一の外側のスコープで に住ん: TestInner.Nonstatic innern= outer.new Nonstatic();

それでは、この問題は次のとおりです。はい、静的メインメソッドでオブジェクトを作成しています。しかし、これは重要ではありません。なぜなら、外側のスコープ内にそれを作成する構文outer.newを使用しているからです。

希望に役立ちます。

+0

@B .Mまた、testinnerObj()メソッドで静的でない内部クラスのオブジェクトを作成しています。正しい方法でもありますか? –

+0

はい、文法上問題ありません。インスタンスメソッド(TestInnerクラスのインスタンス)の中にある 'outer.testinnerObj();'を呼び出しているからです。 –