Is it possible to instantiate a class to null?
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Thanks_forHelp
Posted On:   Thursday, February 1, 2007 08:07 PM

Suppose I create objectA using objB, but if objB meet certain criteria, I want objectA to be null.

			
E.g.

...
objA a = new objA(objB);
if (objA != null) {
...
}


Of course I can check for that criteria before I instantiate objA, but what if I want to build this check in objA?

If this is do-able, how would the constructor of classA look like?

Re: Is it possible to instantiate a class to null?

Posted By:   Robert_Lybarger  
Posted On:   Thursday, February 1, 2007 09:19 PM

You can't do it directly via a constructor, and your terminology is a little off: being instantiated means it isn't null. (That is, you cannot "instantiate to null".) You can use a static "factory" method, however:

public class objA {
public objA() {
/* usual constructor code here*/
}

public static objA newInstance(objB blah) {
if ( /* some condition here */ ) {
return new objA();
}
else {
return null;
}
}
}

Now use the static method instead of a direct constructor:

objB someB;
...
objA someA = objA.newInstance(someB);
...
About | Sitemap | Contact