Can we extend Java record

Can Java record be extended?

Java record introduced in java 14. It provides a way to reduce boiler plate code while defining data classes. record is final implicitly and cannot be extended.
For example in the following record MobilePhone, we cannot extend it.
record MobilePhone
record MobilePhone(String brand, String modelName, Number osVersion, boolean canFlip) {

}
Java records are implicitly final it can be confirmed by the following code. Which checks if the java.lang.Class for the object have final modifier or not.
RecordFinalTest
package Java14;

import java.lang.reflect.Modifier;

public class RecordFinalTest {

	public static void main(String[] args) {
		
		MobilePhone phone1 = new MobilePhone("Samsung", "Galaxy1", 1, false);

		//false
		System.out.println(Modifier.isFinal(phone1.getClass().getModifiers()));
		
		//false
		System.out.println(Modifier.isFinal(MobilePhone.class.getModifiers()));

	}

}
For more details about record in Java please check the following references.

References

No comments :

Post a Comment

Please leave your message queries or suggetions.