Field with same names from parent class and implemented interface and just inside one class difference

1.8k views Asked by At

research 2 code snippets

Snippet 1:

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

this code compiles normally.

snippet2

class Pparent{
    String str = "123";
    public static String str = "123"; 

}

result: compile error with message

variable str is already defined in class

Resolution

for me both snippets looks like same.

Why does I see different results

update for Abimaran Kugathasan

you say:

Fields in interface are implicitly public static, and there not inherited to sub class

contr-example:

interface Int1{
    String str = "123";
}
class F implements Int1{
    public static void main(String[] args) {
        System.out.println(F.str);
    }
}

I cannot write so

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

why? I work with static content only.

2

There are 2 answers

4
Jon Skeet On BEST ANSWER

for me both snippets looks like same.

They're clearly not the same. In your second snippet, you've got two variable declarations for the same name in the same class. That's a violation of this part of section 8.3 of the JLS:

It is a compile-time error for the body of a class declaration to declare two fields with the same name.

In the first snippet, you're declaring one (implicitly static field in the interface and one field in the class. That doesn't violate any rules. Instead, it just follows this rule, also in section 8.3:

If the class declares a field with a certain name, then the declaration of that field is said to hide any and all accessible declarations of fields with the same name in superclasses, and superinterfaces of the class.

2
Abimaran Kugathasan On

Fields in interface are implicitly public static, and there not inherited to sub class. So no conflicts.

In the second case, both fields are in the same class, so there will be conflicts. And compiler complains. as JLS says,

It is a compile-time error for the body of a class declaration to declare two fields with the same name.

Updated Answer based on updated question

interface Int1{
    String str = "123";
}
class F implements Int1{
    public static void main(String[] args) {
        System.out.println(F.str);
    }
}

Here, you aren't inheriting the field, you just access it, because, it's public and static, compiler will automatically change F.str to Int1.str.

In Java, static and inheritance won't work together.