-2
interface Z{ int x = 10;}

Class A implements Z{}

Class B implements Z{}

How java use x in this case?

Does java generate single copy of x, because x is static final? Or different copies for Class A and Class B?

Umesh Chhabra
  • 268
  • 1
  • 8
  • 1
    Would be easy to test! Try it. – olivergregorius Apr 08 '19 at 04:28
  • Possibly related: [What are the rules dictating the inheritance of static variables in Java?](https://stackoverflow.com/questions/9898097/what-are-the-rules-dictating-the-inheritance-of-static-variables-in-java) – Slaw Apr 08 '19 at 06:39

1 Answers1

2

As JLS says about static fields:

If a field is declared static, there exists exactly one incarnation of the field, no matter how many instances (possibly zero) of the class may eventually be created.

About fields inheritance:

A class inherits from its direct superclass and direct superinterfaces all the non-private fields of the superclass and superinterfaces that are both accessible to code in the class and not hidden by a declaration in the class.

There is no special case about static fields inheritance, so they have to be inherited too.

We cannot write a good representative code sample with an interface, because of its variables are implicitly declared as static final. So, let's write a sample with superclass. Say we have:

class Base {
    static int x = 15;
}

class A extends Base {}

class B extends Base {}

The x variable is shared part of Base class. If we think about inheritance in terms of IS-A relationship, then A (or B) is Base. Then x is shared part of A, B and Base. And simple demo:

public class DemoApplication {

    public static void main(String[] args) {
        System.out.println(A.x++);
        System.out.println(B.x);
    }
}

Output:

15
16

As you can see, superclass shares a static variable with subclasses. And with an interface actually nothing changes.

ilinykhma
  • 980
  • 1
  • 8
  • 14