004 关键字record

以下这行代码可以写在一个单独的文件Point.java内,也可以写在某个函数内。

 1 record Point(int x, int y) { } 

它等价于如下代码:

 1 class Point {
 2     private final int x;
 3     private final int y;
 4 
 5     Point(int x, int y) {
 6         this.x = x;
 7         this.y = y;
 8     }
 9 
10     int x() { return x; }
11     int y() { return y; }
12 
13     public boolean equals(Object o) {
14         if (!(o instanceof Point)) return false;
15         Point other = (Point) o;
16         return other.x == x && other.y == y;
17     }
18 
19     public int hashCode() {
20         return Objects.hash(x, y);
21     }
22 
23     public String toString() {
24         return String.format("Point[x=%d, y=%d]", x, y);
25     }
26 }

还可以在其内增加成员方法,但不能增加成员变量。

 1 record Point(int x, int y) {
 2 
 3     public static void main(String[] args) {
 4         Point pointA = new Point(3,4);
 5         System.out.println(pointA);
 6 
 7         Point pointB = pointA.move(2,6);
 8         System.out.println(pointB);
 9 
10     }
11 
12     public Point move(int deltaX, int deltaY){
13         return new Point(x()+deltaX, y() + deltaY);
14     }
15 }

上面的代码将输出

Point[x=3, y=4]
Point[x=5, y=10]

更多的内容请参见 https://openjdk.org/jeps/395

posted @ 2022-12-19 19:37  面包车  阅读(39)  评论(0)    收藏  举报