| Author |
a parameterised constructor that is not returning an object
|
Manohar Reddy Gopireddy
Greenhorn
Joined: Feb 16, 2011
Posts: 9
|
|
Recently I have faced a question in one of my interviews. Here is that.
Suppose say i am having a class TestConstructor, and this class is having a parameterised constructor which takes an int as a parameter.
I am using this class somewhere else in my program as follows
here if a is negative then the constructor should not return any object. that means tc is not referring any object.
can you please suggest me how to resolve this problem?
Thanks in advance
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
Constructors either throw an exception or lead to a successfully created object. There are no other choices when using public constructors.
You can start using factory methods instead. Make the constructor(s) private (or protected if you need to allow sub classing):
Still, throwing exceptions (IllegalArgumentException) from the constructor is not uncommon if anyone provides wrong input to it.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
Manohar Reddy Gopireddy
Greenhorn
Joined: Feb 16, 2011
Posts: 9
|
|
|
Thank you very much Rob
|
 |
Campbell Ritchie
Sheriff
Joined: Oct 13, 2005
Posts: 32694
|
|
|
I would prefer to throw an ExceptionNote that there is no need for an else after the if. You should describe the Exception in the documentation comments.
|
 |
 |
|
|
subject: a parameterised constructor that is not returning an object
|
|
|