In this post under Java, I will show with example how to add and access static members in Java Record.
Below is the structure of “Student” Record with static members
Student
1 package core.record;
2
3 public record Student(int id, String name, int age) {
4 public static int noOfStudents;
5 public static void display() {
6 System.out.println("Number of students: " + noOfStudents);
7 }
8 }
As shown in the above code, we can add static members to Record in the same way we add to a Class.
Below is the main class that shows how we can access the static members of the Record.
Main class
package core.record;
public class Example2 {
public static void main(String[] args) {
Student student = new Student(1, "john doe", 40);
Student.noOfStudents = 1;
System.out.println(student);
Student.display();
}
}
As shown in the above main class, accessing static members of Record, is similar to way we access static members of a class.
That is we don’t need instance of Record, the Record name itself will suffice.
In this way we can add and access static members of a Record