java - Interface ambiguously inherited fields -


i going through jls section 9.3.1 , came across interesting concept of ambigious inherited fields. example jls

interface basecolors { int red = 1, green = 2, blue = 4; } interface rainbowcolors extends basecolors { int yellow = 3, orange = 5, indigo = 6, violet = 7; } interface printcolors extends basecolors { int yellow = 8, cyan = 16, magenta = 32; } interface lotsofcolors extends rainbowcolors, printcolors { int fuchsia = 17, vermilion = 43, chartreuse = red+90; } 

it allowing have ambiguous fields inherited. when try reference field , access it, gives compile time error. giving compile time error ambigious fields. question is, @ first point why compiler didn't complain when ambigious field inherited. why @ access time, it's giving issue? if same when using classes., allows. why not in case of interfaces. point shouldn't allow @ first instant only. clarification on concept pretty helpful.

interface fields implicitely static final. , static fields never inherited. can hide field defining new field same name, need qualify field name appropriate interface resolve conflict:

printcolors.yellow 

or

rainbowcolors.yellow 

edit:

to clarify (hopefully):

the compiler allows use lotsofcolors.magenta in source code, although field defined in printcolors.magenta. that's make life bit easier, when reference field superclass in subclass.

in byte-code, though, compiler replaces reference lotsofcolors.magenta reference printcolors.magenta. happens @ compilation time, , not @ runtime polymorphic methods.

when have ambiguity (like lotsofcolors.yellow), compiler can't decide of fields want use. can printcolors.yellow or rainbowcolors.yellow. so, instead of taking arbitrary decision, compiler produces compilation error, force resolve ambiguity. , resolve ambiguity in source code providing actual class name, either printcolors.yellow or rainbowcolors.yellow.


Comments

Popular posts from this blog

php - Calling a template part from a post -

Firefox SVG shape not printing when it has stroke -

How to mention the localhost in android -