代码之家  ›  专栏  ›  技术社区  ›  DCR

带参数的Java私有构造函数[重复]

  •  0
  • DCR  · 技术社区  · 6 年前

    新问题。在java中有一个带参数的私有构造函数有意义吗?既然私有构造函数只能在类中访问,那么任何参数都不必是该类的实例变量吗?

    2 回复  |  直到 6 年前
        1
  •  2
  •   Mark Rotteveel    6 年前

    是的,如果您打算在类本身的某个方法中使用该构造函数,并像在 单子

    public class MySingleTon {    
        private static MySingleTon myObj;
        private String creator;
        private MySingleTon(String creator){
             this.creator = creator;
        }
        public static MySingleTon getInstance(String creator){
            if(myObj == null){
                myObj = new MySingleTon(creator);
            }
            return myObj;
        }
        public static void main(String a[]){
            MySingleTon st = MySingleTon.getInstance("DCR");
        } 
    }
    
        2
  •  1
  •   davidxxx    6 年前

    假设你有多个 public private 建造师。
    因此,在 私有的 构造函数是有意义的。

    例如:

    public class Foo{
    
       private int x;
       private int y;
    
       public Foo(int x, int y, StringBuilder name){
          this(x, y);
          // ... specific processing
       } 
    
       public Foo(int x, int y, String name){
          this(x, y);
          // ... specific processing
       } 
    
       private Foo(int x, int y){
          this.x = x;
          this.y = y;
       } 
    }