如何避免在Java中创建对象? [英] How to avoid the creation of object in Java?

查看:59
本文介绍了如何避免在Java中创建对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Java编程的新手,我有一个类,为此类我创建了两个对象(obj1,obj2).我不想创建除这些对象以外的对象,如果有人想为该对象再创建一个对象此类仅应引用第一个或第二个对象(而不是创建另一个对象).如何执行此操作?请参考下面的代码

I am new to java programming,I have one class,for this class i created two object(obj1,obj2).i don't want to create other than these object,if any body wants to create one more object for this class that should refer to first,or second objects only(instead of creating one more object).how to do this?please refer below code

class B 
{ 
 void mymethod()
     {  
       System.out.println("B class method");
          } 
 }   
class Myclass extends B
{ 
 public static void main(String s[])
     {  
       B  obj1=new B();//this is obj1
       B  obj2=new B();//this is obj1
       B  obj3=new B();//don't allow to create this and refer this to obj1 or obj2
          } 
 }

谢谢 阿扎姆

推荐答案

查看 Singleton 设计模式.

这篇关于如何避免在Java中创建对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆