• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

why is this?

 
Holmes Wong
Ranch Hand
Posts: 163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
why the following code prints out "Sample", could you explain the strange code line at (1). Thanks.
 
chafule razgul
Ranch Hand
Posts: 63
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if you want to refer to a class variable via the class name, eg Test4.something then by definition something is a class variable. But since flag is an instance variable (non-static) you can still refer to it via the class name, except that you need to flag it with this, as in the example, Test.this.flag
Hope this helps
 
Holmes Wong
Ranch Hand
Posts: 163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks. My question is about the following snippet actually:

You see a semicolon after if statement, and sample
method is inside a pair of braces. Is this allowed inside inner classes?
 
Padma Shyam
Greenhorn
Posts: 7
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
if (Test4.this.flag);
The variable flag of the outer class is referred inside the inner class by Test4.this.flag.
Since there is a semicolon at the end of the 'if' statement,the if condition ends there.
The next statement is the call to the sample() method.So,it displays Sample.If you remove that semicolon and run the program,the boolean condition of 'if' is false and so there is no output.
 
Brian Lugo
Ranch Hand
Posts: 165
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can have block statements in a method/inner class/top-level class ...etc :
BTW - { ... } is a block statement.
void foo() {
{
System.out.println("I'm in a block haha");
}
}
There is nothing wrong with it.
Brian
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic