This week's book giveaway is in the Agile and other Processes forum.
We're giving away four copies of The Mikado Method and have Ola Ellnestam and Daniel Brolund on-line!
See this thread for details.
The moose likes Java in General and the fly likes a parameterised constructor that is not returning an object Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of The Mikado Method this week in the Agile and other Processes forum!
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "a parameterised constructor that is not returning an object" Watch "a parameterised constructor that is not returning an object" New topic
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
    
    4
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.
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: a parameterised constructor that is not returning an object
 
Similar Threads
protected constructors
Overloading constructors with differing intializations
Constructor
Dynamic Constructor Selection
Bad code - Help me fix it