Java 17 Recipes


Download 3.2 Mb.
Pdf ko'rish
bet36/245
Sana02.06.2024
Hajmi3.2 Mb.
#1839910
1   ...   32   33   34   35   36   37   38   39   ...   245
Bog'liq
Java 17 Recipes

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 


59

Download 3.2 Mb.

Do'stlaringiz bilan baham:
1   ...   32   33   34   35   36   37   38   39   ...   245




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling