Win a copy of Escape Velocity: Better Metrics for Agile Teams this week in the Agile and Other Processes forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Liutauras Vilda
  • Tim Cooke
  • Paul Clapham
  • Jeanne Boyarsky
Sheriffs:
  • Ron McLeod
  • Frank Carver
  • Junilu Lacar
Saloon Keepers:
  • Stephan van Hulst
  • Tim Moores
  • Tim Holloway
  • Al Hobbs
  • Carey Brown
Bartenders:
  • Piet Souris
  • Frits Walraven
  • fred rosenberger

a parameterised constructor that is not returning an object

 
Greenhorn
Posts: 10
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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

 
Sheriff
Posts: 22684
128
Eclipse IDE Spring VI Editor Chrome Java Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
Thank you very much Rob
 
Marshal
Posts: 76489
366
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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.
 
permaculture is largely about replacing oil with people. And one tiny ad:
Garden Master Course kickstarter
https://coderanch.com/t/754577/Garden-Master-kickstarter
reply
    Bookmark Topic Watch Topic
  • New Topic