About Question enthuware.ocpjp.v17.2.3696 :

Help and support on OCA OCP Java Programmer Certification Questions
1Z0-808, 1Z0-809, 1Z0-815, 1Z0-816, 1Z0-817

Moderator: admin

Post Reply
kabanvau
Posts: 14
Joined: Thu Nov 21, 2019 5:48 am
Contact:

About Question enthuware.ocpjp.v17.2.3696 :

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

admin
Site Admin
Posts: 10036
Joined: Fri Sep 10, 2010 9:26 pm
Contact:

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

Post 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.
If you like our products and services, please help us by posting your review here.

Post Reply

Who is online

Users browsing this forum: Bing [Bot] and 44 guests