• Post Reply Bookmark Topic Watch Topic
  • New Topic

Don't instantiate class is some condition is true  RSS feed

 
John Landon
Ranch Hand
Posts: 239
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,
I am doing:

I want to get null in the object if some condition is true. The access to this condition is from within ClassA implementation (my implementation). So I cannot know anything if I am not inside ClassA. So the only way tocheck this condition is either static block or the constructor (OR maybe other way?). But how do I "return" null instead of instantiated object?

Thanks.
 
Paul Clapham
Sheriff
Posts: 22829
43
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You don't return null. The "new X()" construct is guaranteed to always return an object of type X, unless an exception is thrown. So you'd have to throw an exception, either in the constructor or in a static initializer. Note that constructors can throw checked exceptions, but static initializers can't, they can only throw unchecked exceptions.

And once you've done any of that, you can't avoid having initialized class X. You can certainly write code so that "new X()" will always throw an exception if it's run on a Tuesday, or whatever condition you want to check for, though.
 
John Landon
Ranch Hand
Posts: 239
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!