Reader small image

You're reading from  Java Coding Problems - Second Edition

Product typeBook
Published inMar 2024
PublisherPackt
ISBN-139781837633944
Edition2nd Edition
Right arrow
Author (1)
Anghel Leonard
Anghel Leonard
author image
Anghel Leonard

Anghel Leonard is a Chief Technology Strategist and independent consultant with 20+ years of experience in the Java ecosystem. In daily work, he is focused on architecting and developing Java distributed applications that empower robust architectures, clean code, and high-performance. Also passionate about coaching, mentoring and technical leadership. He is the author of several books, videos and dozens of articles related to Java technologies.
Read more about Anghel Leonard

Right arrow

90. Adding more artifacts in a record

So far, we know how to add an explicit canonical/compact constructor into a Java record. What else can we add? Well, for example, we can add instance methods as in any typical class. In the following code, we add an instance method that returns the weight converted from grams to kilograms:

public record MelonRecord(String type, float weight) {
  public float weightToKg() {
    return weight / 1_000;
  }
}

You can call weightToKg() exactly as you call any other instance method of your classes:

MelonRecord melon = new MelonRecord("Cantaloupe", 2600);
// 2600.0 g = 2.6 Kg
System.out.println(melon.weight() + " g = " 
  + melon.weightToKg() + " Kg"); 

Besides instance methods, we can add static fields and methods as well. Check out this code:

public record MelonRecord(String type, float weight) {
  private static final String DEFAULT_MELON_TYPE = "Crenshaw";
  private static final float...
lock icon
The rest of the page is locked
Previous PageNext Page
You have been reading a chapter from
Java Coding Problems - Second Edition
Published in: Mar 2024Publisher: PacktISBN-13: 9781837633944

Author (1)

author image
Anghel Leonard

Anghel Leonard is a Chief Technology Strategist and independent consultant with 20+ years of experience in the Java ecosystem. In daily work, he is focused on architecting and developing Java distributed applications that empower robust architectures, clean code, and high-performance. Also passionate about coaching, mentoring and technical leadership. He is the author of several books, videos and dozens of articles related to Java technologies.
Read more about Anghel Leonard