0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Java: record class とは?

Last updated at Posted at 2025-02-23

record class とは

特徴

  • フィールドがイミュータブル(private final)
    • 一度インスタンス化した後に、値を変更できない
  • 下記が自動的に作成される
    • コンストラクタ
    • getter
    • equals
    • hashCode
    • toString

使い方

// クラス名の前にrecordをつける
record Rectangle(double length, double width) { }

下記の記述と同等

// record使わない場合
public final class Rectangle {
    private final double length;
    private final double width;

    public Rectangle(double length, double width) {
        this.length = length;
        this.width = width;
    }

    double length() { return this.length; }
    double width()  { return this.width; }

    // Implementation of equals() and hashCode(), which specify
    // that two record objects are equal if they
    // are of the same type and contain equal field values.
    public boolean equals...
    public int hashCode...

    // An implementation of toString() that returns a string
    // representation of all the record class's fields,
    // including their names.
    public String toString() {...}
}

使用場面

  • 不変でシンプルなデータを持ちたい時
  • 計算処理や状態遷移などを行わない時

参考

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?