Page 1 of 1
					
				About Question enthuware.ocpjp.v21.2.3696 :
				Posted: Sun Jan 26, 2025 6:45 am
				by mouadA
				this statement is not true for me
A record may inherit fields and methods from an interface.
cause interfaces can't have instance fields and static fields are not inherited anyway, correct me if i am wrong, thanks
 
			 
			
					
				Re: About Question enthuware.ocpjp.v21.2.3696 :
				Posted: Sun Jan 26, 2025 8:50 am
				by admin
				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,
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 
    }
}
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.
 
			 
			
					
				Re: About Question enthuware.ocpjp.v21.2.3696 :
				Posted: Mon Feb 10, 2025 4:06 am
				by driedbars
				mouadA wrote: ↑Sun Jan 26, 2025 6:45 am
this statement is not true for me
A record may inherit fields and methods from an interface.
cause interfaces can't have instance fields and static fields are not inherited anyway, correct me if i am wrong, thanks
 
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.