• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

overriding Interface variables

 
Douglas Cyporyn
Greenhorn
Posts: 21
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I read that interfaces can declare variables and they are implicitly public, final and static. Therefore interface variables are constants.

Okay. So then what are the implications for the implementing class regarding the interface variables? I had assumed the same override rules that apply to methods would apply to the interface variables such that these constants cannot be overridden (because they are marked final). But clearly I am mistaken.

This interface:



is implemented by this class:



now, by commenting out the instance variable in the class Programmer such as this:



Clearly the interface variable is coming into scope here.

Am I doing it wrong? Perhaps I need to revisit the rules for inheriting/overriding instance variables. Any additional thoughts on this one?

Thank you.
 
Roel De Nijs
Sheriff
Posts: 10662
144
AngularJS Chrome Eclipse IDE Hibernate Java jQuery MySQL Database Spring Tomcat Server
  • Likes 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can NEVER override a variable. It doesn't matter if the variable is defined in an interface and/or a class, you simply can't override a variable. Only methods can be overridden! That's a 1st (very) important rule, you should remember.

But you can hide (or shadow) a variable. And that's what you see in your example. The PASSING_SCORE variable in class Programmer looks exactly the same as the one in the Certifiable interface, but isn't. It's just another variable which happens to have the same name as the variable defined in the interface. So the variable in the Programmer class is hiding/shadowing the one in the Certifiable interface. Easily illustrated when you change the writePracticeExam method a little bit:


And there was another pointer in your example to prove it wasn't an override: to have a valid override the access modifier can never be more restrictive than the one definied. So all methods & variables in your interface are inheritly public, but the variable in Programmer has default access level (which is more restrictive than public). So because you could compile & run the program, this could not be an override

Hope it helps!
 
Douglas Cyporyn
Greenhorn
Posts: 21
4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you, it helps a lot! I will review override rules once again. I missed somewhere that override does not apply to variables.

Thanks!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic