JAVA_IIBRARY Telegram 1689
Автоматический toString() в Record

record сравнительно новая фича в Java, которая позволяет описывать сущности без явного объявления полей и написания геттеров/сеттеров.

Пример:

record User(String name, int age, String city) { }


Если писать это же через класс, получится больше кода:

class User {
public String name;
public int age;
public String city;

public User(String name, int age, String city) {
this.name = name;
this.age = age;
this.city = city;
}
}


И в том и в другом случае мы получаем объект для хранения данных:

new User("Nick", 20, "New York");


Но есть отличие

У record метод toString() генерируется автоматически и выводит имена и значения всех полей в удобном формате.

В обычном классе дефолтный toString() возвращает имя класса и хэш объекта.

Пример:

record User(String name, int age, String city) { }

class SecondUser {
public String name;
public int age;
public String city;

public SecondUser(String name, int age, String city) {
this.name = name;
this.age = age;
this.city = city;
}
}

public static void main(String[] args) throws Exception {
User firstUser = new User("Nick", 20, "New York");
SecondUser secondUser = new SecondUser("Charley", 25, "New York");

System.out.println(firstUser);
System.out.println(secondUser);
}


Вывод:

User[name=Nick, age=20, city=New York]
org.example.SecondUser@68de145


То есть у record toString() сразу готов, а для обычного класса придётся переопределять вручную.

👉 Java Portal
Please open Telegram to view this post
VIEW IN TELEGRAM
🔥13👍4



tgoop.com/Java_Iibrary/1689
Create:
Last Update:

Автоматический toString() в Record

record сравнительно новая фича в Java, которая позволяет описывать сущности без явного объявления полей и написания геттеров/сеттеров.

Пример:

record User(String name, int age, String city) { }


Если писать это же через класс, получится больше кода:

class User {
public String name;
public int age;
public String city;

public User(String name, int age, String city) {
this.name = name;
this.age = age;
this.city = city;
}
}


И в том и в другом случае мы получаем объект для хранения данных:

new User("Nick", 20, "New York");


Но есть отличие

У record метод toString() генерируется автоматически и выводит имена и значения всех полей в удобном формате.

В обычном классе дефолтный toString() возвращает имя класса и хэш объекта.

Пример:

record User(String name, int age, String city) { }

class SecondUser {
public String name;
public int age;
public String city;

public SecondUser(String name, int age, String city) {
this.name = name;
this.age = age;
this.city = city;
}
}

public static void main(String[] args) throws Exception {
User firstUser = new User("Nick", 20, "New York");
SecondUser secondUser = new SecondUser("Charley", 25, "New York");

System.out.println(firstUser);
System.out.println(secondUser);
}


Вывод:

User[name=Nick, age=20, city=New York]
org.example.SecondUser@68de145


То есть у record toString() сразу готов, а для обычного класса придётся переопределять вручную.

👉 Java Portal

BY Java Portal | Программирование


Share with your friend now:
tgoop.com/Java_Iibrary/1689

View MORE
Open in Telegram


Telegram News

Date: |

Telegram Channels requirements & features Over 33,000 people sent out over 1,000 doxxing messages in the group. Although the administrators tried to delete all of the messages, the posting speed was far too much for them to keep up. 2How to set up a Telegram channel? (A step-by-step tutorial) While the character limit is 255, try to fit into 200 characters. This way, users will be able to take in your text fast and efficiently. Reveal the essence of your channel and provide contact information. For example, you can add a bot name, link to your pricing plans, etc. In handing down the sentence yesterday, deputy judge Peter Hui Shiu-keung of the district court said that even if Ng did not post the messages, he cannot shirk responsibility as the owner and administrator of such a big group for allowing these messages that incite illegal behaviors to exist.
from us


Telegram Java Portal | Программирование
FROM American