It is possible to add as many class
types as necessary for a Java program. But for clarity of the code, and ease of maintenance, using records to reduce code size is possible.
With the record keyword, we can create a class
with multiple fields. An optional constructor, with simplified syntax, can also be added for validation.
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.
ShopEntry
record has a String
and an int
, and it is defined within the Program
class
. We create an instance of ShopEntry
.ShopEntry2
record type locally, and create an instance of it. Records have special code to print out their values.ShopEntry3
and call toUpperCase
in its constructor.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]
For complicated types with many uses in a program, a class
is probably worth creating. But if a type is only used in one place, and is simple, a record is a good option.
instanceof
operator with records, to determine whether an Object is an instance of a certain record.Much like records in other object-oriented programming languages, the records in Java provide a lightweight, low-syntax class
type. They can be used like classes in most ways.