Java 类中具有不同访问修饰符的两个构造函数。有什么用?

Java 类中具有不同访问修饰符的两个构造函数。有什么用?,java,constructor,access-modifiers,Java,Constructor,Access Modifiers,使用两个具有不同访问修饰符的构造函数有意义吗。确切的用途是什么?例如: public class Apple { int count; public Apple() { } private Apple(int count) { this.count = count; } public void count() { System.out.println("Apple count is"

使用两个具有不同访问修饰符的构造函数有意义吗。确切的用途是什么?例如:

public class Apple {

    int count;

    public Apple()
    {

    }

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

    public void count()
    {
        System.out.println("Apple count is" + count); 
    }
}
无论使用哪种构造函数,我们都可以从类右侧访问所有内容

例如,在本例中,您无法控制
Apple
实例的
count
是什么(从类本身之外的任何地方),因为注入
count
值的构造函数是
private
,并且
count
字段本身具有默认访问权限

确切的用途是什么

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;
}

私有构造函数可以由公共构造函数调用。如果您希望在每个构造函数中执行相同的处理,但不希望只允许使用该处理进行构造,那么它非常有用。按ex:

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
    }
    }

您也可以在静态工厂中使用私有构造函数。

从类中可以,但访问修饰符都是关于控制类用户看到的内容。这很有意义,但与类中没有区别。请参见中的第一列。如果想要阻止其他类使用
Apple(int count)
构造函数,并确保它们使用无参数构造函数,这种方法将非常有意义。