Source of ClassVsRecord.java


  1: //ClassVsRecord.java
  2: //Java records are new in Java 16.

  4: //The goal of the Java record is to provide a minimal way to declare
  5: //immutable classes. It allows declaration of types with a canonical
  6: //set of values, while implementing all the obvious boilerplate code
  7: //(accessors, hashCode, equals, toString) automatically.
  8: /*
  9: More specifically the goals include:
 10: 1. Devise an object-oriented construct that expresses a
 11:    simple aggregation of values.
 12: 2. Help developers to focus on modeling immutable data
 13:    rather than extensible behavior.
 14: 3. Automatically implement data-driven methods such as
 15:    equals and accessors.
 16: */

 18: import java.util.Objects;

 20: public class ClassVsRecord
 21: {
 22:     public static void main(String[] args)
 23:     {
 24:         PersonClass objPersonClass = new PersonClass("John", 28);
 25:         System.out.println(objPersonClass);
 26:         System.out.println(objPersonClass.getName());
 27:         System.out.println(objPersonClass.getAge());

 29:         PersonRecord objPersonRecord = new PersonRecord("Alice", 25);
 30:         System.out.println(objPersonRecord);
 31:         System.out.println(objPersonRecord.name());
 32:         System.out.println(objPersonRecord.age());
 33:     }
 34: }

 36: class PersonClass
 37: {
 38:     private String name;
 39:     private int age;

 41:     public PersonClass(String name, int age)
 42:     {
 43:         this.name = name;
 44:         this.age = age;
 45:     }

 47:     public String getName()
 48:     {
 49:         return name;
 50:     }

 52:     public int getAge()
 53:     {
 54:         return age;
 55:     }

 57:     @Override
 58:     public String toString()
 59:     {
 60:         return "PersonClass{" +
 61:                "name='" + name + '\'' +
 62:                ", age=" + age +
 63:                '}';
 64:     }

 66:     @Override
 67:     public int hashCode()
 68:     {
 69:         return Objects.hash(name, age);
 70:     }

 72:     @Override
 73:     public boolean equals(Object obj)
 74:     {
 75:         if (this == obj) return true;
 76:         if (obj == null || getClass() != obj.getClass()) return false;
 77:         PersonClass objPersonClass = (PersonClass) obj;
 78:         return age == objPersonClass.age &&
 79:                Objects.equals(name, objPersonClass.name);
 80:     }
 81: }

 83: record PersonRecord(String name, int age)
 84: {
 85:     // No need to explicitly declare constructors,
 86:     // getters, toString, hashCode, or equals.
 87: }