2013-04-12 39 views
3

假設我有一個內部類B,我將在外部類的成員函數內創建一個實例,是否有一種方法可以在沒有創建一個外部類的實例?只在成員函數內創建一個嵌套內部類的對象

非常感謝。

class A { 
    class B { 

    } 

    public void function() { 
     // create an instance of B, normally have to create a 
     // instance of A to be bond to by b 
     B b = new B(); 
    } 
} 
+0

B截取如A的靜態 –

回答

2

你做到這一點的唯一方法是通過聲明Bstatic

class A { 
    static class B { 

這意味着B不具有與它相關聯A一個實例,並且可以在上下文中實例化在沒有外可用的實例。

這就是說,當前的代碼編譯罰款,是(因爲function()是非static,有在這方面提供的A一個實例)。

0

如果您在外部類的方法內訪問嵌套/內部類,則不需要創建外部類的實例。

1

可以從class A之外創建的class B對象像

B B =新A()新B()。

但是,在這裏您正在創建外部類的實例,然後創建內部類的實例。如果不創建外部類的實例,則不可能創建內部對象。

但是如果你的內部類是static那麼你可以做到這一點。

class A { 
    static class B { 

    } 
} 
class C{ 
    public void test(){ 
     B b = new B(); 
    } 
} 
0

您可以直接的class A成員函數中創建的class B一個實例。實際上class B就像是一個成員(A的變量/函數),如果Class A。它可以像其他成員一樣直接訪問。所以在

public void function() { 
    // create an instance of B, normally have to create a 
    // instance of A to be bond to by b 
    B b = new B(); 
} 

沒有問題,如果你想的class A範圍之外創建的class B實例,那麼只需要的class A實例像這樣

A a = new A(); 
B b = a.new B(); 

創建class B的實例假設您想在class A的範圍之外創建class B的實例,但不包含class A的實例,則將class B聲明爲靜態,這意味着class B不在的範圍內

class A { 
    static class B { 
    } 

    public static void main(String[] args) { 
     B b = new B(); 
    } 
} 
0

如果您在nested class不是靜態的,那麼答案是沒有。因爲:

Inner class treated as instance member of outer class. 

所以只有這樣,才能創建內部類的實例,首先創建的外實例那麼只有你可以在內部類創建實例。就像下面:

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

但有一種方法,而無需創建外部類對象,爲您的內部類應該是static nested class創建內部類對象。如下。

class Outer { 
static class Inner { 

然後,可以像以下創建內部類的對象:

Inner inner = Outer.new Inner(); 

becase的:

Static nested class always treated as static member of outer class.