Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

interface rule

 
muks verma
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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();}
}

if interface variables implicitly become static and finale then how come in above code it is changing.
 
Shaliey Gowtham
Ranch Hand
Posts: 104
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Static members are not inherited.
The variables declared are all different variables and have no resemblence to the interface variable
 
Amirr Rafique
Ranch Hand
Posts: 324
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi
If a class has same varibale as defined in its parent class or Interface that it implements then the inherited variable is shadowed. So here value of interface varibale is not being changed rather it is being shadowed.

Hope it helps
 
IM Mahesh
Greenhorn
Posts: 18
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What has been changed by the code?
What result r u expecting?

As per the rules output should be : ABCI

Don't forget that the interface variable s1 is static and hence would not be overriden by the subclasses. Therefore the subclasses will always refer to there own copy. And you are accessing it in a nonstatic way through the instance.
 
muks verma
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot to all guys who replied very fast,now i have better understanding of overriding.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic