• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Tim Cooke
  • paul wheaton
  • Jeanne Boyarsky
  • Ron McLeod
Sheriffs:
  • Paul Clapham
  • Liutauras Vilda
  • Devaka Cooray
Saloon Keepers:
  • Tim Holloway
  • Roland Mueller
Bartenders:

Doubt in an Interface Question!!

 
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Ranch Hand
Posts: 1865
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
What? What, what, what? What what tiny ad:
Smokeless wood heat with a rocket mass heater
https://woodheat.net
reply
    Bookmark Topic Watch Topic
  • New Topic