Win a copy of Learning Regular Expressions this week in the General Computing 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 all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Liutauras Vilda
  • Campbell Ritchie
  • Tim Cooke
  • Bear Bibeault
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Knute Snortum
  • Junilu Lacar
Saloon Keepers:
  • Tim Moores
  • Ganesh Patekar
  • Stephan van Hulst
  • Pete Letkeman
  • Carey Brown
Bartenders:
  • Tim Holloway
  • Ron McLeod
  • Vijitha Kumara

Constructor calling another constructor  RSS feed

 
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Hi folks,

Can you please take a look at the above code? I could forget this and move on but it's like an existential question for me I know that another constructor can be called only by this() putting it on the first line of the constructor. Please help me understand WHY is the numPaws = 4 ignored and how this happens.
 
Bartender
Posts: 3320
86
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The main method creates a new instance if Cat by calling the no argument constructor which creates a new instance of Cat by calling the Cat int argument constructor and then throws that object away. The no args constructor then completes without setting the instance variable numberPaws.
 
Saloon Keeper
Posts: 4758
117
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You probably meant line 9 to read "this(4);", which invokes the other constructor without creating another object.
 
Ranch Hand
Posts: 461
22
Android Chrome Eclipse IDE Google App Engine Java Notepad Oracle Ubuntu Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
calling a constructor and creating an object are two different things.object is created when we invoke a new operator before the constructor call.you may be thinking that a constructor call is an object creation but it is not.To make it concrete think about an abstract class which also has a constructor.but you can't instantiate it as compiler will not allow you to invoke "new" on its constructor.
in your case when you have created a cat c by invoking the new on parameter less constructor,their in the call of constructor another cat,say it d,gets created which has the value of numberpaws=4.but as it didn't touch the numberpaws for c so it has the default value=0.

HIH

Kind Regards,
Praveen.
 
Consider Paul's rocket mass heater.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!