Use of private Constructor.

  This  program  explain  how we can declare   private constructor . Vary   simple   explain
 taking  two   class  to access the  data  declared. 

public class     Myconstrct {

           private Myconstrct() { 

            System.out.println("default private constructor");


          private Myconstrct(int x) { 

                    System.out.println(" overloaded private constructor. " +x); 

            Myconstrct(String x){

                       System.out.print("This Not Private Constr::" +x);


      /* public static void main(String args[])

                Myconstrct t1 = new Myconstrct();
               Myconstrct t2 = new Myconstrct(49);



 If  run this   it  will  give  out put  as 

          default private constructor

         overloaded private constructor. 49

But   if  you  use   try  to create  instance in  other class of private 
constructor  it  will give error.

        public class privatetest {

      public static void main(String[] args) {
        // TODO Auto-generated method stub

        // Myconstrct t1 = new Myconstrct(); error 

             Myconstrct t2 = new  Myconstrct("MukeshJha");


  Program  output  for  this  short of code will be 
   This Not Private Constr::MukeshJha

Use of private Constructor. Use  of private Constructor. Reviewed by Mukesh Jha on 5:27 AM Rating: 5

No comments:

Add your comment

All Right Reserved To Mukesh Jha.. Theme images by Jason Morrow. Powered by Blogger.