私有構造函數可以通過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
}
}
您可以使用靜態工廠的私有構造函數了。
來源
2016-06-20 10:27:35
sab
從類yes,但訪問修飾符都是關於控制類的用戶看到的。 – Tunaki
這很有意義,但它與班級*無關。請參見[本表](http://stackoverflow.com/a/33627846/276052)中的第一列。如果想阻止其他類使用'Apple(int count)'構造函數,並確保它們使用無參數構造函數,那麼這種方法將非常合理。 – aioobe