• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Anon Inner Class ??

 
Rick Roberts
Ranch Hand
Posts: 59
Hibernate Java Redhat
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just when I thought I had it all figured out.
I come across a question like this:

package rroberts;
public class AnonInner3 {

public static void main( String[] args ) {
class A {
String name = "bob";
}
A a = new A() {
String name = "notbob";
};
System.out.println( a.name );
}
}

The result is:

A. bob
B. notbob
C. compile error
D. runtime error

I know the answer is bob; but I dont understand why.
It seems that it would be notbob.
Anyone care to enlighten me?

Thanks
 
Keith Lynn
Ranch Hand
Posts: 2409
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Since instance variables are hidden in subclasses, and the reference type of a is A, the instance variable that is referred to by the name a.name will be the one in class A.
 
wise owen
Ranch Hand
Posts: 2023
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Run time binding or compile time binding?

Instance variables, static variables, static overridden methods (it looks like it's an override, but actually hidden), and overloaded methods are all bound at compile time; and this kind of binding depends on the type of the reference variable and not on the object.

[ September 27, 2006: Message edited by: wise owen ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic