Skip to content

Records

Info

Semua file yang ada pada contoh pada catatan ini ada pada package Ch4/J4_5_Records

Record Concept

record adalah bentuk sepsial dari sebuah class dimana statenya adalah immutable dan readeable pada public.

record Employee (String name, int id, LocalDate hireDay, BigDecimal salary){}

Hasilnya adalah sebuah class dengan instance fields serta accessor method sebagai berikut;

public class Employee{

    private final String name;
    private final int id;
    private final Calendar hireDay;
    private final BigDecimal salary;

    public Employee (String name, int id, Calendar hireDay, BigDecimal salary){
        this.name = name;
        this.id = id;
        this.hireDay = hireDay;
        this.salary = salary;
    }
    public String name(){
        return this.name;
    }
    public int id(){
        return this.id;
    }
    public Calendar hireDay(){
        return this.hireDay;
    }
    public BigDecimal salary(){
        return this.salary;
    }
}

Setiap record memiliki tiga buah method yang telah terdefinisi secara otomatis, toString(), equals(), dan hashCode.

12.1 3 Method Records.png

Kita juga dapat membuat method sendiri pada sebuah record

record Employee (String name, int id, LocalDate hireDay, BigDecimal salary){

    public void raisingSalary(BigDecimal kenaikan){
        this.salary.add(kenaikan);
    }

}

Sebagaimana class, record juga dapat memiliki static fields dan methods

private static int incrementalPointByCalledMethod = 0;

public static int getTotalIncrementalpointByCalledMethod(){
    return incrementalPointByCalledMethod;
}

Akan tetapi kita tidak dapat menambahkan instance fields

Not Allowd instance field

Kita juga dapat meng-override method yang diturunkan oleh records.

@Override
    public String toString() {
        incrementalPointByCalledMethod++;   
        return "Name\t\t: %s\nid\t\t: %d\nHire day\t:%s\nSalary\t\t: %,d"
                .formatted(name, id, hireDay, salary);
    }

Ingat, instance fields dari record secara otomatis menjadi final (nilainya tidak dapat berubah). Namun untuk instance field record yang menampung object references rasanya akan seperti variable mutable. Namun sesunggunya variable tersebut tetap final.

Code

package Ch4.J_4_5_Records.J_1_ConceptRecords;

import java.math.BigDecimal;
import java.util.Calendar;

public class MainRecords {
    public static void main(String[] args) {

        Calendar dayHire = Calendar.getInstance();
        dayHire.set(2023,6,5);

        var employeeFarras = new Employee("Farras",2745, dayHire,
                new BigDecimal(13_000_000));

        System.out.println(employeeFarras);

        System.out.println("----");
        // Ganti hireDay
        employeeFarras.hireDay().add(Calendar.DAY_OF_MONTH,10);
        System.out.println(employeeFarras);
    }
}
Output
Name        : Farras
id          : 2745
Hire day    : Wed Jul 05 00:06:23 WIB 2023
Salary      : 13,000,000
----
Name        : Farras
id          : 2745
Hire day    : Sat Jul 15 00:06:23 WIB 2023
Salary      : 13,000,000

Tip

Gunakan record dari pada class untuk objek yang datanya tidak dibutuhkan untuk berubah-ubah (immutable). Gunakan class jika datanya memungkinkan untuk berubah. Record lebih mudah dibaca dan lebih efesiend serta aman untuk concurrent program (progmram yang berbarengan).

Consructor : Canonical, Costume and Compact

Constructor yang secara otomatis terdefinisi (seperti record) dengan caramemasang semua instance fields dengan paramter disebut dengan canonical constructor.

Kita juga dapat mendefinisikan costum constructor tambahan. Statement constructor pertama harus memanggil constructor lainnya.

Code

record Point (double x, double y ){

    public Point(){
        this(0,0);
    }
    ...
}

Record diatas memiliki 2 buah constructore, pertama adalah original constructor yang menerima dua buah parameter, sedangakan yang kedua adalah construcotr yang tidak menerima parameter apapun.

Jika canonical constructor membutuhkan perkerjaan tambahan kita dapat menyediakan implementasi kita sendiri.

Code

record Point (double x, double y ){

    public Point(double x , double y){
        if (y > x){
            this.x = y;
            this.y = x;
        }
        else {
            this.x = x;
            this.y = y;
        }
    }
}

However, you are encouraged to use a compact form when implementing the canonical constructor.

Code

record Range(int from, int to){
    public Range{
        if (to <=  from){

            int temp = from;
            from = to;
            to = temp;
        }
    }
}

Badan dari compact form adalah prelude (Pendahuluan) untuk canonical constructor. Pendahuluan tersebut sebenarnya memodifikasi parameter variable sebelum di assigned ke instance fields this.from dan this.to. Dan, Kita tidak dapat membaca read atau memodifikasi instance fields didalam body of compact constructore.

All Code

package Ch4.J_4_5_Records;

public class J_2_Canonical_Costume {
    public static void main(String[] args) {

        Point p1 = new Point(4d,3d);
        System.out.printf("X : %.2f\nY : %.2f\n",p1.x(),p1.y());System.out.println();

        Point p2 = new Point();
        System.out.printf("X : %.2f\nY : %.2f\n",p2.x(),p2.y());System.out.println();

        Point p3 = new Point(3d, 12d);
        System.out.printf("X : %.2f\nY : %.2f\n",p3.x(),p3.y());System.out.println();


        Range range1 = new Range(10,20);
        System.out.printf("From : %d\nTo : %d\n",range1.from(), range1.to());System.out.println();

        Range range2 = new Range(40,20);
        System.out.printf("From : %d\nTo : %d\n",range2.from(), range2.to());

    }
}

record Range(int from, int to){
    public Range{
        if (to <=  from){

            int temp = from;
            from = to;
            to = temp;
        }
    }
}

record Point (double x, double y ){

    public Point(){
        this(0,0);
    }

    public Point(double x , double y){
        if (y > x){
            this.x = y;
            this.y = x;
        }
        else {
            this.x = x;
            this.y = y;
        }
    }
}
Output
X : 4.00
Y : 3.00

X : 0.00
Y : 0.00

X : 12.00
Y : 3.00

From : 10
To : 20

From : 20
To : 40