Hank Mooody
Hank Mooody

Reputation: 527

How to ensure that new instance of class can be created only by other class?

I know that title is little bit to long, so here is my problem . I've got this class for example:

public  class Connection
{
     public static Connection Create()
     {
          return new Connection();
     }            
}

I need to ensure that new instances of Connection can be created only by other classes , calling the Create method.The solution must allow classes to inherit from Connection.

Some of the answers I've found is to make class abstract or static but as I remember, you can't make instance of abstract or static class nor inherit from static.

The other two offered answers is to make private or protected constructor of Connection class.Well, if constructor is set on private , we can't call him from derived class , but if it is protected, we can .

So , my idea is to make constructor protected.Am i right ?Because I found that someone posted making Connection class static is right answer, and that doesn't make any sense .

Upvotes: 1

Views: 1864

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726509

Both static and abstract are out for the reasons that you outlined in your question. The way to let other classes inherit from yours, while prohibiting direct instantiation is to make the constructor protected. Keep in mind, however, that an inheriting class can choose to allow its own constructor to be public, thus circumventing your protection.

In general, though, a class should be designed either for inheritance or for instantiation, but not for both purposes at the same time. A better design would be as follows:

public abstract class Connection {
    protected Connection();
    public static Connection Create() {
        return new DefaultConnection();
    }
}
internal sealed class DefaultConnection : Connection {
    public DefaultConnection() {
        ...
    }
}

Classes from outside can inherit Connection, but they cannot instantiate it because it's abstract. Your code, on the other hand, can create instances of DefaultConnection, which is hidden from everybody else because it is internal.

Upvotes: 2

Som Shekhar
Som Shekhar

Reputation: 138

If you create it as a child class in main class, set the constructor to take a parameter which is generated internally in main class and verified using a private method in main class.

This way no external class can't instantiate the child class without throwing an exception.

Upvotes: 0

Related Questions