Manoj Kumar Jain wrote:You can mark the class as abstract..
That's not a good approach. It doesn't clearly express your real intent. Abstract classes are intended to be extended, with the concrete subclass being instantiated. That means we will have an instance of the base class, because child IS-A parent.
Joined: Feb 19, 2011
Suppose i write this:
/* some code here*/
now i want that no one can create the object of this class.
how can i do this?
Personally, I'd throw an AssertionError, as that is code that should never be executed. As in, "It shouldn't be possible to get here."
Joined: Oct 13, 2005
AssertionError, ThreadDeath and probably other subtypes of Error seem to me to occupy a very strange place in their inheritance trees.
But it probably has the same effect irrespective of whichever kind of unchecked Exception you throw. If you had a checked Exception that would be obvious from the documentation because it would display the throws clause.
Campbell RitchieIf you had a checked Exception that would be obvious from the documentation because it would display the[tt wrote: throws [/tt]clause.
I don't think a checked exception is needed here. The fact that it's private should be all the documentation needed.
And if you really want to document it, you can still add a throws clause for the unchecked exception. I suppose with a checked exception you'd at least be forced to add the throws clause. I don't consider a checked exception appropriate here though.
Joined: Oct 13, 2005
I think we agree you wouldn’t want a checked Exception in those circumstances.
Sorry to offend your sensibilities. But not really.
Although I guess an assert statement would be fine too. Sure, it can be turned off at runtime, but that's only gonna matter if somebody is deliberately using reflection to invoke a c'tor they know they shouldn't be, so if you do that and it lets you and stuff breaks, too bad. It's not the kind of thing I would concern myself with protecting against. Honestly, I wouldn't even do anything beyond making the c'tor private. It's easy to get carried away with defensive programming.
Joined: Mar 12, 2011
Jeff Verdegan wrote:Honestly, I wouldn't even do anything beyond making the c'tor private. It's easy to get carried away with defensive programming.