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?
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?
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.