プライベートコンストラクタは、パブリックコンストラクタによって呼び出すことができます。コンストラクタのそれぞれで同じ扱いをしたいのであれば便利ですが、処理だけで構築することはできません。 By:
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
クラスからはい、しかしアクセス修飾子は、クラスのユーザーが見るものを制御についてのすべてです。 – Tunaki
これは理にかなっていますが、クラス内の*とは何の違いもありません。 [この表](http://stackoverflow.com/a/33627846/276052)の最初の列を参照してください。彼らは引数なしのコンストラクタを使用してください代わりに 'アップル(int型の数)'コンストラクタを使用してから他のクラスを防止したい場合は、このアプローチは完璧な理にかなって。 – aioobe