This week's book giveaway is in the OCMJEA forum.
We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Doubt in an Interface Question!! Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Doubt in an Interface Question!!" Watch "Doubt in an Interface Question!!" New topic
Author

Doubt in an Interface Question!!

Sharanya Sharma
Ranch Hand

Joined: Jul 26, 2004
Posts: 54
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

Joined: Jul 02, 2002
Posts: 1865
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.


Dan Chisholm<br />SCJP 1.4<br /> <br /><a href="http://www.danchisholm.net/" target="_blank" rel="nofollow">Try my mock exam.</a>
Sharanya Sharma
Ranch Hand

Joined: Jul 26, 2004
Posts: 54
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
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Doubt in an Interface Question!!