• Post Reply Bookmark Topic Watch Topic
  • New Topic

Constructor not executing? Help !!  RSS feed

 
Ranch Hand
Posts: 132
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the following code, I was expecting text "In the first class!!" to get printed. It is not printing this text.

Can you please help me to understand this please ?

class tst
{
public static void main(String ara[])
{
tst t = new tst();
new first();

class first
{
first()
{
System.out.println("In the first class!!");
}
}

}
}
 
Ranch Hand
Posts: 46
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I can't even compile that, much less get the message you expect to print out. I believe it won't compile because the first class is defined within the same method that you call new first(). I think solving that problem comes first. I can get it to compile and print the message if I move the declaration for the "first" class outside of the declaration of the tst class. Like so:
 
Ranch Hand
Posts: 4632
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
 
Ranch Hand
Posts: 823
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The text is not printed because the code doesn't compile. :roll: The code doesn't compile because the class first is a local inner class, i.e. a local declaration. It must therefore be declared (defined) before it is referenced. Moving the call to the constructor first() to after the local class definition, as in Michael's example, allows the code to compile and produce the expected output.

Jules
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!