what will happen if fields with same name inherites from two sources(class and interface)

拜拜、爱过 提交于 2020-01-06 08:42:03

问题


valid code:

interface Int1{
    String str = "123";
}
class Pparent{
    String str = "123";  
}
class F extends Pparent implements Int1{       
}

invalid code

add main method to F class:

class F extends Pparent implements Int1{
      public static void main(String[] args) {
        System.out.println(str);
    } 
}

outs

Exception in thread "main" java.lang.Error: Unresolved compilation problem: 
  The field str is ambiguous

  at test.core.F.main(NullReferenceTest.java:45)

I don't see striking differs beetwen both variants. I prepare to scjp and ask to clarify all related situations. When I see familiar question I am messed.

Can you clarify common rule ?


回答1:


There are two fields which the identifier str can refer to - a static one inherited from Int1, and an instance one inherited from Pparent. Even though it's invalid to try to use the instance one from a static context, the name can still be resolved. (If Pparent.str were static, you'd still get the error message.)

Neither field is hiding the other, because they're inherited from different parents - so the name is ambiguous. The compiler's complaining because it doesn't know which field you mean.

If you want the one from Int1, just qualify it:

System.out.println(Int1.str);

If you want the one from Pparent, you should create an instance and cast it to Pparent to make it clear you're not referring to the interface field:

System.out.println(((Pparent) new F()).str);

Obviously this is horrible, and you should avoid getting into such situations in the first place. This is partly achieved by making all fields private, except constants. It's very unusual to have two constants with exactly the same name in both a superclass and an interface you want to implement.




回答2:


The str field of your interface Int1 is implicitly static public and final.

The str field of your Pparent class is an instance field.

What happens when you reference str is you have an ambiguous reference to the instance field and the class field, hence the error.




回答3:


You are trying to run code inside Eclipse which has an error. Eclipse generates code to produce that message.

You are invoking that code generated by Eclipse. Your original source was erroneous, so the Eclipse compiler could not compile it - instead byte code has been generated that shows the message in the question.

Realistically,this is a Compile time error.




回答4:


I believe this is not allowed , as value of str would be ambiguous between your PParent class and Int1 ,this will give you compile time errors as you are getting currently.This is a case of multiple inheritence of variables.



来源:https://stackoverflow.com/questions/23810509/what-will-happen-if-fields-with-same-name-inherites-from-two-sourcesclass-and-i

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!