• Post Reply Bookmark Topic Watch Topic
  • New Topic

a parameterised constructor that is not returning an object  RSS feed

 
Manohar Reddy Gopireddy
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 21135
87
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Manohar Reddy Gopireddy
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you very much Rob
 
Campbell Ritchie
Marshal
Posts: 56584
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!