aspose 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


Win a copy of Spring in Action this week in the Spring forum!
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: 19722
    
  20

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: 3647
    
  17

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: 19722
    
  20

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
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Overriding Interface constant in an implementing class.