About Question enthuware.ocpjp.v21.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
mouadA
Posts: 2
Joined: Fri Dec 27, 2024 8:08 am
Contact:

About Question enthuware.ocpjp.v21.2.3696 :

Post 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

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

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

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

driedbars
Posts: 1
Joined: Mon Feb 10, 2025 3:55 am
Contact:

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

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

Post Reply

Who is online

Users browsing this forum: Bing [Bot], nkaragulov and 11 guests