Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Agile forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

overriding member fields in interfaces

 
Michael Wiezik
Ranch Hand
Posts: 70
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Suppose I have this bit of code:


interface I1{
String s1 = "It is implicitly final...";
}

interface I2 extends I1 {
String s1 = "...so why can I override it?";
}

Could anybody give formal explanation why can I override interface member fields, although they are final?
 
Chandra Vadlamani
Ranch Hand
Posts: 31
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Over riding is not applicable to member variables unless they are methods. Members which are either references to primitives or objects are being shadowed and in order to access I1 related members you have to do I1.member and same with I2. With methods it is a different story. Both at run time and compile time reference is the one that decides which variable will be used.

Hope that clears some confusion.
 
Praveen Singh
Greenhorn
Posts: 14
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can always define a new variable with the same name either in a class that implements an interface or in a interface that extends an interface,

it wiil be valid to write something :

interface I1{
String s1 = "It is implicitly final...";
}

interface I2 extends I1 {
String s1 = "...so why can I override it?";
// Here u r defining a new variable s1, valid
}

but following will give error :

interface I1{
String s1 = "It is implicitly final...";
}

interface I2 extends I1 {
s1 = "...so why can I override it?";
// Here u r trying to change the value of s1 that final and is already defined in super interface.
}

Hope this clears..
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic