加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

如何调用被私有化的构造方法

(2012-04-13 22:18:21)
标签:

it

分类: IT

 

一个构造方法如果被私有化了,那么只能从该私有化类的内部进行实例化进行调用

class Con1{

   

    private static Con1 ins = new Con1();    //内部实例化构造方法;

    public static Con1 getIns(){ //通过静态方法获取实例化对象

        return ins;

    }

    private Con1(){ //私有化构造方法

       

    }

    public void print(){

        System.out.print("成功实例化");

    }

}

 

public class ConstructDemo {

   

    public static void main(String args[]){

        Con1 con1= null;

        con1 = Con1.getIns(); //取得实例化对象

        con1.print();

       

    }

私有化构造方法是一种单态设计方法,可以实现避免多次实例化;如:

public class ConstructDemo {

 

public static void main(String args[]){

 

 

Con1 con1= con1 = Con1.getIns();

Con1 con2= con1 = Con1.getIns();

Con1 con3= con1 = Con1.getIns();

Con1 con4= con1 = Con1.getIns();

Con1 con5= con1 = Con1.getIns();

       

con1.print();

con2.print();

con3.print();

con4.print();

con5.print();

   }

}

该功能的实现实际上只实例化了一次而已:private static Con1 ins = new Con1();    //内部实例化构造方法;

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有