twid
twid

Reputation: 6686

how to make class to not allow creating new object (new Object())

I am developing a library and I don't want the user to create an instance of a class directly with the new keyword, instead I have special methods to create objects. So is it possible if the user instantiates a class using the new keyword, that the compiler gives error. For Example:

public class MyClass {
    private MyClass(int i) {  }

    public MyClass createMyClassInt(int i) {
        return new MyClass(i);
    }

    private MyClass(double d) { }

    public MyClass createMyClassDouble(double d) {
        return new MyClass(d);
    }
}

So when the user tries to instantiate MyClass myClass = new MyClass();, the compiler will give an error.

Upvotes: 4

Views: 3499

Answers (2)

user902383
user902383

Reputation: 8640

if you want to create your class by special method why dont use factory design pattern? static method inside your class which returns you new instance of class

if you just dont want to create new class by default constructor, and you want to force user to use one with parameter, then just don't implement default constructor

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1500165

Your code is nearly fine - all you need is to make your create methods static, and give them a return type:

public static MyClass createMyClassInt(int i) {
  return new MyClass(i);
}

public static MyClass createMyClassDouble(double d) {
  return new MyClass(d);
}

The methods have to be static so that the caller doesn't already have to have a reference to an instance in order to create a new instance :)

EDIT: As noted in comments, it's probably also worth making the class final.

Upvotes: 11

Related Questions