2013-02-01 72 views
3

我怎樣才能改變這種實現:如何保護類直接實例化

public interface Animal() 
{ 
    public void eat(); 
} 

public class Dog implements Animal 
{ 
    public void eat() 
    {} 
} 

public void main() 
{ 
    // Animal can be instantiated like this: 
    Animal dog = new Dog(); 

    // But I dont want the user to create an instance like this, how can I prevent this declaration? 
    Dog anotherDog = new Dog(); 
} 
+0

修正刪除__()__從__implements動物(){__即改變**實現動物(){**它**實現動物{** – Visruth

回答

7

創建一個工廠方法和保護構造:

public class Dog implements Animal { 
    protected Dog() { 
    } 

    public static Animal createAsAnimal() { 
     new Dog(); 
    } 
} 
+2

你可能會想使構造函數'private'來禁止子類化。 – Natix

+0

你是對的Natix。 @Alexander Pogrebnyak,我們仍然可以保持對象類型爲狗,不是嗎?!!! 例如:__Dog anotherDog = ....__ – Visruth

+0

@Natix。 OP沒有說明「Dog」是否應該被分類,或者不是。我認爲,這可能是因爲OP在示例中沒有宣佈它是「最終」。在最後一個''Dog'類的情況下,我絕對會聲明構造函數'private' –

1

通過創建如下你可以這樣做工廠方法:

public interface Animal { 
    public void eat(); 

    public class Factory { 
    public static Animal getAnimal() { 
     return new Dog(); 
    } 
     private static class Dog implements Animal { 
      public void eat() { 
       System.out.println("eats"); 
      } 
     } 
    } 
} 

Dog類對用戶不可見。 運行:

Animal dog= Animal.Factory.getAnimal(); 
dog.eat();//eats