Page 1 of 1

About Question enthuware.ocpjp.v17.2.3696 :

Posted: Sat Jun 11, 2022 4:57 am
by kabanvau
A record may inherit fields and methods from an interface.

I thought, the public static fields from interfaces cannot be inherited. All instances of that record will share the same static variables.

Re: About Question enthuware.ocpjp.v17.2.3696 :

Posted: Sat Jun 11, 2022 11:52 am
by admin
It is true that fields of an interface are not inherited by a class in the same sense that instance fields of a super class are inherited. However, in case of static members (fields as well as methods), the inheritance is about the ability to access those fields using subclass/implementing class. For example,

Code: Select all

interface I{
    int X = 10; //implicitly static and final
}

record R(int a) implements I { };

class Main{
    public static void main(String[] args) {
        R r = new R(1);
        System.out.println(r.X); //this works even though r does not really have its personal copy of X
    }
}
So, even though there is just one copy of static fields, they are kind of inherited by the implementing class in a way.

Even JLS in section 8.10.3 says:
...
All of the rules concerning inheritance that apply to normal classes apply to record
classes. In particular, record classes may inherit members from superinterfaces, ...
Here, "members" implies methods and fields.