• Post Reply Bookmark Topic Watch Topic
  • New Topic

Constructor calling another constructor  RSS feed

 
Laimonas Oberauskis
Greenhorn
Posts: 9
  • 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.
 
Tony Docherty
Bartender
Posts: 3271
82
  • 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.
 
Tim Moores
Saloon Keeper
Posts: 4024
94
  • 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.
 
praveen kumaar
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.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!