Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How "reject" instancing a class

Tags:

java

c++

For example,

public class Test {
    Test() {
    if(xxx)//do some check here
        //reject instancing class test.
    }
}

I think I can throw a exception to reject it, is there any other way? I am not sure what's the effect of instancing been rejected, but I think a natural way is:

Test test = new Test();//return null here indicating instancing rejected.

I expect java and C++ all should have this "reject" feature.

like image 765
Helin Wang Avatar asked May 17 '26 04:05

Helin Wang


2 Answers

If you want to return null you could get use of Factory pattern. E.g. instead of Test test = new Test(); you could write Test test = TestFactory.CreateTest();, and implement all the checks you need in TestFactory.CreateTest.

new Test() always returns a non-null instance of Test (at least in Java).

like image 88
penartur Avatar answered May 19 '26 17:05

penartur


You can't return null from a constructor, but you can (as you suggest) throw an exception.