Shrikant
Shrikant

Reputation: 1

Avoid Object Creation in Java

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();
      }
 }

Upvotes: 0

Views: 1656

Answers (5)

Kuntal-G
Kuntal-G

Reputation: 2981

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();

    }

Upvotes: 4

Eran
Eran

Reputation: 393841

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.

Upvotes: 2

Mr.Chowdary
Mr.Chowdary

Reputation: 3407

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,

Upvotes: 5

Devavrata
Devavrata

Reputation: 1785

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

Upvotes: 4

user2357112
user2357112

Reputation: 280857

private A() {}

Make the constructor private.

Upvotes: 1

Related Questions