0

How to stop other classes to create the object of the class using new operator in java. For Example, i have one class A. i don't want any other class to create its object using new operator.

One Approach is that i can throw IllegalArgumentException in the constructor of class A.

is there any other?

 public class A{

      public A(){
        throw IllegalArguementException();
      }
 }
1

5 Answers 5

5

The approach what you followed is wrong.. you can't create object of your class as well with this approach.
So you must make your construction private and write static method to get the instance of the class.

class Test
{
    private Test(){ }

    public static Test getTestInstance(){
        return new Test();
    }
}  

Hope it helps,

Sign up to request clarification or add additional context in comments.

Comments

4

You can do it by making the constructor private.

class A
{
     int i;
     private A()
     {
          i=1;
     }
     public static A getInstance()
     {
          return new A();
     }
 }
 class B
 {
     A a;
     public B()
     {
     /*    a=new A();   //This doesn't compile */
     }
 }

Comments

4

Implementing Singleton in Java 5 or above version using Enum is thread safe and implementation of Singleton through Enum ensures that your singleton will have only one instance even in a multithreaded environment.

public enum SingletonEnum {
 INSTANCE;
 public void doYourStuff(){
     System.out.println("Singleton using Enum");
 }
}

And this can be called from clients :

public static void main(String[] args) {
        SingletonEnum.INSTANCE.doYourStuff();

    }

Comments

2

You can make the class abstract (though in this case no instance of this class can be instantiated by any class, so perhaps it's not what you want), or make the constructor private.

Comments

1
private A() {}

Make the constructor private.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.