cause interfaces can't have instance fields and static fields are not inherited anyway, correct me if i am wrong, thanksA record may inherit fields and methods from an interface.
About Question enthuware.ocpjp.v21.2.3696 :
Moderator: admin
-
- Posts: 2
- Joined: Fri Dec 27, 2024 8:08 am
- Contact:
About Question enthuware.ocpjp.v21.2.3696 :
this statement is not true for me
-
- Site Admin
- Posts: 10384
- Joined: Fri Sep 10, 2010 9:26 pm
- Contact:
Re: About Question enthuware.ocpjp.v21.2.3696 :
An interface can have default methods and static fields. Both can be inherited by a record.
Although fields of an interface are static and are not inherited in the same sense as fields of a regular super class but they are inherited from an access point of view. For example,
In the above code , you can see that method m() is inherited and field XX of the interface is being accessed using the reference rx.
Although fields of an interface are static and are not inherited in the same sense as fields of a regular super class but they are inherited from an access point of view. For example,
Code: Select all
public class TestClass {
interface X {
int XX = 10;
default void m() {
System.out.println("In X.m");
}
}
record RX(String s) implements X { }
public static void main(String[] args) throws Exception {
RX rx = new RX("hello");
rx.m(); //prints In X.m
System.out.println(rx.XX); //prints 10
}
}
-
- Posts: 1
- Joined: Mon Feb 10, 2025 3:55 am
- Contact:
Re: About Question enthuware.ocpjp.v21.2.3696 :
You're correct! Interfaces in Java have only static final fields, which are not inherited. Records can implement interfaces and inherit default methods but never fields. Thus, the statement about records inheriting fields from an interface is incorrect.
Who is online
Users browsing this forum: Bing [Bot], nkaragulov and 11 guests