44
loading...
This website collects cookies to deliver better user experience
Index | Way to update record | Java language features preventing it |
---|---|---|
1 | Create a record sub-class and change the state of the sub-class. | Record classes are implicitly final and can not be abstract, this way we can not create a sub-class of the record class. |
2 | Extend some other class(superclass) and change the state of the superclass. | All record classes extend java.lang.Record by default so can not extend any other class. |
3 | Add instance fields that can be modified. | Record classes cannot declare instance fields. |
4 | Update record components. | We can not assign a new value to record components as these are implicitly final. These are assigned values while initializing the record in a canonical constructor. |
5 | Update record components in the constructor. | Only canonical constructor can update record components, which is called while initializing record. For other types of constructors, assigning any of the record components in the constructor body results in a compile-time error. |
6 | Update record components using reflection. | Record components have specific handling in Reflection Field API. This treatment is like hidden classes. You can read more about Hidden classes here. |
public class EmployeeTest {
public static void main(String[] args) {
List<Integer> integerList = new ArrayList<>();
integerList.add(1);
IntegerListRecord integerListRecord = new IntegerListRecord(integerList);
System.out.println(integerListRecord.getListSize());
integerList.add(2);
System.out.println(integerListRecord.getListSize());
}
}
record IntegerListRecord(List<Integer> integerList) {
int getListSize()
{
return integerList.size();
}
}