This Java program defines 3 different records, and then creates one instance of each of them. Records can be defined at the class level, or locally within a method.
public class Program {
// Created in main.
record ShopEntry (String name, int cost) {}
public static void main(String[] args) {
// Part 1: create new entry from class-level record.
ShopEntry s = new ShopEntry(
"shoes", 200);
System.out.println(s);
// Part 2: use local record and create an instance of it.
record ShopEntry2 (String name, int size) {}
ShopEntry2 s2 = new ShopEntry2(
"pants", 40);
System.out.println(s2);
// Part 3: use local record with simplified constructor.
record ShopEntry3 (String name, int id) {
ShopEntry3 {
name = name.toUpperCase();
id = id;
}
}
ShopEntry3 s3 = new ShopEntry3(
"hat", 30);
System.out.println(s3);
}
}
ShopEntry[name=shoes, cost=200]
ShopEntry2[name=pants, size=40]
ShopEntry3[name=HAT, id=30]