views:

53

answers:

1

If we execute run the following code, the output is 10.


interface X{
 int abc = 0;
}
interface XX extends X{
 int abc = 10;
}
class XTest implements XX
{
 public static void main(String[] args) 
 {
  System.out.println("Hello World! --> " +abc);
 }
}

But as per Java, interface variables are public static final. but how am I getting 10 as output?

+5  A: 

This code works as it should.

Your XTest class implements XX, so it gets the value of abc from the public static final instance in that interface.

XX shadows X, so it supercedes the abc value from X.

duffymo
Thanks duffymo,does shadows means override?If yes, we can't overrides public static final variables right?can you please give some more clarification? Or any pointers to any article?
Mohammed
It's not exactly "overiding". This might clarify: http://java.sun.com/docs/books/jls/second_edition/html/names.doc.html
duffymo
'Shadows' means more like replaces and hides than overrides but the effect is similar in this case. The abc in XX replaces and hides the abc in X. The abc in X is still there though. Classes that implement XX would have to refer to X.abc to see the 0 value.
Skip Head
Mohammed