File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes interface rule Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "interface rule" Watch "interface rule" New topic

interface rule

muks verma

Joined: Mar 10, 2004
Posts: 3
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.

Shoot for the moon, even if u miss u will land among stars.
Shaliey Gowtham
Ranch Hand

Joined: Mar 20, 2006
Posts: 104
Static members are not inherited.
The variables declared are all different variables and have no resemblence to the interface variable
Amirr Rafique
Ranch Hand

Joined: Nov 14, 2005
Posts: 324
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

"Know where to find the solution and how to use it - that's the secret of success."
IM Mahesh

Joined: Mar 09, 2006
Posts: 18
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

Joined: Mar 10, 2004
Posts: 3
Thanks a lot to all guys who replied very fast,now i have better understanding of overriding.
I agree. Here's the link:
subject: interface rule
It's not a secret anymore!