2016-06-20 27 views
-3

使用兩個具有不同訪問修飾符的構造函數是否合理?什麼是確切的用途?對於如:在一個類中具有不同訪問修飾符的兩個構造函數。有什麼用?

public class Apple { 

    int count; 

    public Apple() 
    { 

    } 

    private Apple(int count) 
    { 
     this.count = count; 
    } 

    public void count() 
    { 
     System.out.println("Apple count is" + count); 
    } 
} 

無論使用哪種構造,我們可以從類訪問的一切權利

+0

從類yes,但訪問修飾符都是關於控制類的用戶看到的。 – Tunaki

+0

這很有意義,但它與班級*無關。請參見[本表](http://stackoverflow.com/a/33627846/276052)中的第一列。如果想阻止其他類使用'Apple(int count)'構造函數,並確保它們使用無參數構造函數,那麼這種方法將非常合理。 – aioobe

回答

2

不是真的之一。

例如,在這種情況下,你無法控制的Apple實例的count是什麼(從超出類本身的任何地方),因爲注入count值的構造是private,並count領域本身具有默認訪問。

0

確切的用法是什麼?

Java的許多其他OOP語言可以讓你的超載,這是不是比讓您自由定義許多方法/構造函數使用不同的參數等,所以你可以在一個非常靈活的方式構建或準備這取決於什麼樣的用戶給出的輸入/用戶需要什麼對象?

的某個時候將只在內部調用方法裏面,隱藏的對象裏面如何變魔術的用戶...

檢查一個使用如何通過執行類似

Apple ap = new Apple(1); 

構建一個蘋果,但也許用戶不必/想通過計數立即

這樣他就可以使用

Apple ap2 = new Apple(); 

的技巧是在默認構造函數(構造函數沒有參數) 裏面,因爲你看到構造函數調用自己並初始化蘋果,但是用count=0;

int count; 

public Apple() 
{ 
    this(0); 
} 

private Apple(int count) 
{ 
    this.count = count; 
} 
0

私有構造函數可以通過public構造函數調用。如果你想在你的每個構造函數中進行相同的處理,但是不希望只允許使用處理來構建它,那麼這很有用。由前:

class Vehicule{ 

    private Vehicule(String name){ 
    this.name=name; 
    } 

    public Vehicule(String name, Motor motor, GazType gazType){ 
    this(name); 
    this.motor=motor; 
    this.gazType=gazType; 
    } 
    public Vehicule(String name,SolarPanel solarPanel){ 
    this(name); 
    this.solarPanel = solarPanel; 
    } 
public Vehicule(String name, int numberOfCyclist){ 
    this(name); 
    this.numberOfCyclist=numberOfCyclist; 
    } 

{ 

     Vehicule car = new Vehicule("ford", engine, gaz);//OK 
     Vehicule tandem = new Vehicule("2wheel2people", 2);//OK 
     Vehicule sailboard = new Vehicule("blueWind", blueSail);//OK 
     Vehicule madMaxCar = new Vehicule("Interceptor", v8Engine, nitroglicerine);//OK 

     Vehicule vehicule=new Vehicule("justeAname")//Compilation Error 
    } 
    } 

您可以使用靜態工廠的私有構造函數了。

相關問題