Java 17 Recipes
Download 3.2 Mb. Pdf ko'rish
|
Java 17 Recipes
- Bu sahifa navigatsiya:
- How It Works
2-6. Using Record
Problem You want to declare classes with simple management of the main and standard methods. Solution Use Record classes, which efficiently model classes. In the following, there is a standard code for an entity class. public class Professor { private Integer id; private String name; private String surname; Chapter 2 enhanCements from Java 9 through Java 17 57 public Professor () { } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getSurname() { return surname; } public void setSurname(String surname) { this.surname = surname; } } Since Java 14, this lengthy class can be defined as follows. record Professor (Integer id, String name, String surname) {} So, you can simply create a new prof. Professor prof = new Professor (1, "Luciano", "Manelli"); And not in a standard old way. Professor prof = new Professor (); prof.setId(1); prof.setName("Luciano"); prof.setSurname("Manelli"); Chapter 2 enhanCements from Java 9 through Java 17 58 The following is the main class. public class Main { public static void main (String[] args) { Professor prof = new Professor (); prof.setId(1); prof.setName("Luciano"); prof.setSurname("Manelli"); System.out.println("Prof "+prof.getId()+":"+prof.getName()+ " "+prof.getSurname()); record ProfessorRecord (Integer id, String name, String surname) {}; ProfessorRecord profRecord = new ProfessorRecord (1, "Luciano", "Manelli"); System.out.println("Prof using Record "+profRecord.id()+ ":"+profRecord.name()+" "+profRecord.surname()); } } How It Works This enhancement was proposed in Java 14 and became a standard feature in Java 16 (JEP 394). It helps developers by providing a compact syntax for declaring classes, avoiding the well-known verbosity of the Java language. In some cases, it is useful to preserve the immutability of data creating equals, hashCode, and toString methods. The first method verifies the equality for objects when all fields match the same class. The second method returns a unique integer value when all fields match. The third method gives a string derived from the name of the class and the names and values of each component. For more information on the Record class, see the documentation at https:// openjdk.java.net/jeps/395 . Chapter 2 enhanCements from Java 9 through Java 17 |
Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling
ma'muriyatiga murojaat qiling