Example of syntax and semantics

Let's redefine the Emp class, which we used at the beginning of the chapter, as a data class:

record Emp(String name, int age) { }      // data class - one liner 
// code

The preceding code uses the record keyword to define a data class, accepting a comma-separated variable name and type, required to store the state. The compiler automatically generates default implements for the object methods (equals(), hashCode(), and toString()) for data classes.

The code looks clear and compact. A reader would immediately know the intent of this single line of code—a carrier of the data name (type String) and age (type int). Another advantage for a reader is that they wouldn't have to read through constructors, accessors, mutators, or methods of the object class, just to ascertain that they are doing what they are supposed to.

Behind the scenes, the record class, Emp, is converted to the following code by the Java compiler:

final class Emp extends java.lang.DataClass {
final String name; final int age;
public Emp(String name, int age) {
this.name = name; this.age = age; } // deconstructor // public
// accessor methods // default implementation of equals,
// hashCode, and toString }

The preceding data class is an example of a non-abstract data class. A data class can also be defined as an abstract data class. A non-abstract data class is implicitly final. In both cases, a data class will get default implementations of hashCode(), equals(), and toString(), and accessor methods. For an abstract data class, the constructors would be protected.

In the following diagram, the compiler looks happy to convert the one line code for the data class to a full-fledged class:

By default, a data class is final; you can't extend it.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.216.117.191