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

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 ?

Jon Skeet
people
quotationmark

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.

people

See more on this question at Stackoverflow