• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Anonymous class problem

 
Prasun Howlader
Ranch Hand
Posts: 89
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
public class Prg{
int i = 12;
public static void main(String[]args){
final int i = 14;
fun(new Prg(){{System.out.println(i);}});
}
public static void fun(Prg ob){}
}
When i run this program it despaly 12 .
1)Why i values in the Prg class dispaly here?
2)How can access local i in the method main?
 
Fu Dong Jia
Ranch Hand
Posts: 131
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,Prasun Howlader
I think the code"System.out.println(i);" should be in a method.
Anonymous class is like the normal class except it`s location.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Jia Fudong:
...I think the code"System.out.println(i);" should be in a method...

It's executing as an initialization block.
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Prasun Howlader:
... When i run this program it despaly 12 .
1)Why i values in the Prg class dispaly here?
2)How can access local i in the method main?

When you define the anonymous class body, note that you are subclassing Prg, so the anonymous instance has an inherited variable 'i' with a value of 12.

I don't think it's possible to reference main's local variable 'i' from the context of this anonymous class body.
 
Kelvin Chenhao Lim
Ranch Hand
Posts: 513
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Prasun Howlader:
1)Why i values in the Prg class dispaly here?
2)How can access local i in the method main?[/QB]


Prasun, thanks for posting a pretty interesting question! As Marc pointed out, the anonymous subclass's i instance variable shadows the local variable in main(), so there's no way to access it directly from the method body.

However, do note one subtle point: the instance variable i is visible within the anonymous subclass because the anonymous subclass is created in a method (main()) within the same package as Prg. However, because you declared i with package-private (i.e. default) visibility, it will not be visible outside the package. In other words:
will output "14", whereas
will output "12" (just like your original code).

Note also that if your original code declared Prg's i instance variable as private, your program will also output "14".
[ November 05, 2007: Message edited by: Kelvin Lim ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic