Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

where is the object created?

 
Sriram Chintapalli
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi all where or when in the following code is the object created when Animal(10) is called:
public class Animal
{
public Animal()
{
super();
}
protected Animal(int legs)
{
this();
}
}
-Thanks
Sriram
 
Vad Fogel
Ranch Hand
Posts: 504
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Sriram Chintapalli:
hi all where or when in the following code is the object created when Animal(10) is called:
public class Animal
{
public Animal()
{
super();
}
protected Animal(int legs)
{
this();
}
}
-Thanks
Sriram

A new object is created by the time all the constructors calls of its class are resolved, i.e. right after the call to this(); returns.
 
Sriram Chintapalli
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for answering Vad. I made a minor change to the program:
public class Animal
{
public Animal()
{
super();
}
protected Animal(int legs)
{
this();
//here
System.out.println("print this");
//or here
}
public static void main(String[] args)
{
Animal a=new Animal(10);
}
}
So the object should be constructed after the print statement(//or here) right???
-sriram
 
Vad Fogel
Ranch Hand
Posts: 504
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Right.
 
Corey McGlone
Ranch Hand
Posts: 3271
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, the way you can confirm this is to throw an exception within the constructor, like this:

Obviously, the object is not created until the constructor is finished executing or m would not be null. Just another way to look at the same thing.
 
Sriram Chintapalli
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thanks a lot Vad!that was a some neat code Corey, thanks!
-sriram
 
Liz Brown
Ranch Hand
Posts: 112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Corey,
Is it necessary to write throw statement inside. I observe some coders just write throws clause (wtihout throw in the method).
is this allowed? if yes, why?
thanks.
Shivan
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic