Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 939
twid Avatar asked Dec 08 '22 21:12

twid


2 Answers

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.

like image 106
Jon Skeet Avatar answered Dec 11 '22 09:12

Jon Skeet


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

like image 41
user902383 Avatar answered Dec 11 '22 09:12

user902383