Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to avoid the creation of object in Java?

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
          } 
 }

Thanks azam

like image 248
user1335578 Avatar asked May 28 '26 18:05

user1335578


2 Answers

Check out the Singleton design pattern.

like image 145
weltraumpirat Avatar answered May 30 '26 08:05

weltraumpirat


What you need is the Singleton design pattern.

Class B should look something like so:

class B
{
    private static B instance = null;

    private B()
    {
         //Do any other initialization here
    }

    public static B getInstance()
    {
        if (instance == null)
        {
            instance = new B();
        }
        return instance;
    }
}

Then, in your Myclass, just do this:

B obj1 = B.getInstance();
B obj2 = B.getInstance();

Note: This is not thread safe. If you are looking for a thread safe solution please consult the Wiki Page.

EDIT: You could also have a static initializer

class B
{
    private static B instance = null;
    static
    {
         instance = new B();
    }


    private B()
    {
         //Do any other initialization here
    }

    public static B getInstance()
    {       
        return instance;
    }
}
like image 28
npinti Avatar answered May 30 '26 06:05

npinti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!