Search code examples
javaparametersprivate-constructor

Java private constructor with parameters


newbe question. Does it make any sense to have a private constructor in java with parameters? Since a private constructor can only be accessed within the class wouldn't any parameters have to be instance variables of that class?


Solution

  • Yes, if you are going to use that constructor in some method of your class itself and expose the method to other class like we do in the singleton pattern. One simple example of that would be like below :

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