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.
About Question enthuware.ocpjp.v17.2.3696 :
Moderator: admin
-
- Posts: 14
- Joined: Thu Nov 21, 2019 5:48 am
- Contact:
-
- Site Admin
- Posts: 10062
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: About Question enthuware.ocpjp.v17.2.3696 :
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,
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:
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
}
}
Even JLS in section 8.10.3 says:
Here, "members" implies methods and fields....
All of the rules concerning inheritance that apply to normal classes apply to record
classes. In particular, record classes may inherit members from superinterfaces, ...
If you like our products and services, please help us by posting your review here.
Who is online
Users browsing this forum: Bing [Bot] and 38 guests