Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Doubt in an Interface Question!!

 
Sharanya Sharma
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Please look at the code below..

interface I {String s1 = "I";}
class A implements I {String s1 = "A";}
class B extends A {String s1 = "B";}
class C extends B {
String s1 = "C";
void printIt() {
System.out.print(((A)this).s1 + ((B)this).s1 +
((C)this).s1 + ((I)this).s1);
}
public static void main (String[] args) {new C().printIt();}
}
What is the result of attempting to compile and run the program?

The answer to the question is given as "ABCI"

But my doubt is that a variable declared in an interface is implicitly public static final. So it should give a compile time error.

Please clarify me if I am wrong.

Thanks,
Sharanya
 
Dan Chisholm
Ranch Hand
Posts: 1865
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sharanya,

You are correct, a variable declared in an interface is implicitly public static final. The "final" modifier means that the value of the variable can not be changed; it is a compile-time constant. A subclass is free to declare a variable that hides a variable that shares the same name in the superclass even when the superclass variable is declared final.

Of course, the rules associated with the final modifier in a method declaration are different.
 
Sharanya Sharma
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Dan,

Thanks for the response. This clarifies my doubt.
As you say if the class A used

S1= "A" //Directly instead of String S1= "A"

it would have been a compiler error.

Thanks
Sharanya
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic