Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Interface variables

 
Kathy Hodgson
Greenhorn
Posts: 28
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This code is from one of Dan Chisolm's single topic practice exams:
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();
}
}
The correct output is given as ABCI, and that's what I get when I run it -- but I had thought it wouldn't even compile because the interface variable s1 is implicitly final and shouldn't be able to be reassigned. What am I missing here?
Thanks,
Kathy
 
Damien Howard
Ranch Hand
Posts: 456
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
S1 is not being reasigned, it is being hidden.
You cannot override a var. When you are casting the object types, you are actually accessing the version of the var that goes with that object type.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic