File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Overriding Interface constant in an implementing class. Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Overriding Interface constant in an implementing class. " Watch "Overriding Interface constant in an implementing class. " New topic
Author

Overriding Interface constant in an implementing class.

Abhijit Ghatnekar
Greenhorn

Joined: Nov 10, 2007
Posts: 19
Hello All,

So its been 4 long years ever since I'm not working in Java ( all these years i was in PHP/Perl/Python and Cold fusion and I'm an SCJP). I was planning to shift to Java again and started reading my old certification book this morning.

I'm stuck at one point.

It is correct that interfaces define constants. But can a class which implements that interface override (or shadow) that variable?

in other words will the below code execute without any error?

And what if I want the values of both the variables in the above code without changing the variable name?

Thank You,
Abhijit.
(I know being an SCJP I should know this, but sorry. I'm completely out of touch )

Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19670
    
  18

Use the interface name: Go.BAR is the constant* from the interface, and this.BAR or BAR is the instance field from the class.

* fields in interfaces are always public, static and final.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3613
    
  14

What happened when you tried compiling that code?
Abhijit Ghatnekar
Greenhorn

Joined: Nov 10, 2007
Posts: 19
@Rob: Thanks, man. after struggling through the code for sometime, I managed to echo out two different values of that constant.. :-).
@Stephan: That code compiled but I was amazed as to how it did and I wanted to confirm whether it is shadowing or it is something else :-)

This forum rocks and of course Java does too.

Cheers,
Abhijit
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19670
    
  18

Abhijit Ghatnekar wrote:@Rob: Thanks, man. after struggling through the code for sometime, I managed to echo out two different values of that constant.. :-).

There are no different values of any constant. That beats the purpose of a constant, doesn't it?
What you meant is that you got one value for the constant and a different value for the instance field.

And you're welcome
 
Consider Paul's rocket mass heater.
 
subject: Overriding Interface constant in an implementing class.