• Post Reply Bookmark Topic Watch Topic
  • New Topic

Variables in interface  RSS feed

 
Abhishek Chhawcharia
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Variables defined in interface are public static and final so I was thinking that we should not be able to override the variables in a class thats implementing the interface.

But when I am compiling the below class, it compiles fine and gives the correct values. but when I did disp.abhi = 35; it gives a compile error (cannot override final variable)




 
Campbell Ritchie
Marshal
Posts: 56536
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can never override fields. You are hiding them. Those are completely new fields which cause you to ignore any fields in the interface.
 
Campbell Ritchie
Marshal
Posts: 56536
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
And welcome to the Ranch

There are other people who waited much more than 5 years between registration and first post
I added code tags to your post: doesn't it look better Always use the tags.
 
Abhishek Chhawcharia
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Ritchie,

Thanks for the reply.

I guess this is what is called as "Shadowing". And yes, I will use tags going forward while posting questions. I have been preparing for 803 certificaion for 2-3 months and trying different combinations to see how will the code behave.

 
Campbell Ritchie
Marshal
Posts: 56536
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome It is called hiding (I am pretty sure); we have an FAQ about it (but that might only cover methods).
 
Stefan Evans
Bartender
Posts: 1837
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The code provided compiles? Really?
It doesn't for me.
On the line:
Error: cannot instantiate the type display

Oh, and the reason for the error you mentioned: As well as being public and static, any variables declared in an interface are also final.
So assigning a new value to them is an error.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!