2017-04-13 80 views
2

我在類Foo中用方法doSomething()創建了一個foo類的實例。標準慣例是在該類中創建一個類的實例嗎?

public class Foo { 
    public void doSomething() { 
     Foo foo1 = new Foo(); 
    } 
} 

這是標準做法嗎?這似乎是一個很不尋常的事情。你爲什麼想要這樣做?以這種方式創建代碼是否存在危險?你是否有理由這樣做,而不是使用其他一些做法?最後,我的直覺是任何做這種事情的方法都應該被聲明爲靜態的。那是對的嗎?

+0

恕我直言,這不是,是非常罕見的(除非該方法是靜態的)。 –

回答

5

是的,這是標準做法。這不是常見(在實例方法中,更常見於static s),但它是完全標準的。

Foo中的代碼在很大程度上是無關緊要的:如果代碼由於某種原因需要Foo以外的其他實例,則創建實例並使用它是非常正常的。

這不是真的比任何一個創建不同類的兩個實例的方法更奇:

class Foo { 
    void method() { 
     Bar b1 = new Bar(); 
     Bar b2 = new Bar(); 
     // ... 
    } 
} 

據推測,method需求都Bar實例。同樣,doSomething顯然需要Foo而不是this

你特別看到的一個地方是具有流暢接口的不可變對象,其中大多數方法都會返回對象的一個​​實例,並改變了某些方面。

public class Thingy { 
    private int a; 
    private int b; 

    public Thingy(a, b) { 
     this.a = a; 
     this.b = b; 
    } 

    public Thingy withA(int newA) { 
     return new Thingy(newA, this.b); 
    } 

    public Thingy withB(int newB) { 
     return new Thingy(this.a, newB); 
    } 

    public int getA() { 
     return this.a; 
    } 

    public int getB() { 
     return this.b; 
    } 

    // ... 
} 

通常withX方法比這更有趣,但你的想法... String就是這樣的一個例子,作爲5tingr4y指出:toUpperCasesubstring,...

+0

@JornVernee:LOL - 我在發帖之後想到了第二個不變性,並添加了它,參見上文。 :-) –

+0

或RecursiveTask :) – HRgiger

+1

字符串將是一個很好的例子。 trim()和subString(...)和東西返回新的字符串。 – 5tingr4y

1

是,沒關係。一個很好的例子是binary tree,它(通常)創建子節點的父節點內增長:

class Node { 
    Node left, right; 
    int value; 
    Node (int i) { 
     value = i; 
    } 
    void add(int i) { 
     if (i < value) 
     left = new Node(i); // must create Nodes within Nodes 
     else 
     right = new Node(i); // must create Nodes within Nodes 
} 
+0

很好的例子。 .. –

相關問題