Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Overriding Interface constant in an implementing class.

 
Abhijit Ghatnekar
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20531
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Stephan van Hulst
Bartender
Pie
Posts: 5813
61
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What happened when you tried compiling that code?
 
Abhijit Ghatnekar
Greenhorn
Posts: 19
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@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
Pie
Posts: 20531
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic