class Point { private double x; private double y; //一个无参构造器 public Point() { x = 0; y = 0; }
//一个自定义构造器 public Point(double x, double y) { x = x; y = y; } // 利用静态变量构造一个原点 // 静态变量属于类,无论实例化了多少个对象都共享类的 //同一个静态变量 public final static Point = new Point();
public class recordTest { public static void main(String[] args) { var p = new Point(3, 4); System.out.println("Coordinates of p:" + p.x() + " " + p.y()); System.out.println("Distance from Origin:" + p.distanceFromOrigin()); System.out.println("Distance from Origin:" + Point.distance(Point.ORIGIN, p)); //记录可以直接将实例化的对象打印 System.out.println(p);
var pt = new PointInTime(3, 4, new Date()); System.out.println("Before: " + pt); pt.when().setTime(0); System.out.println("After: " + pt);
var r = new Range(4, 3); System.out.println("r: " + r); } }
record Point(double x, double y) { //无参构造器 public Point() { this(0,0); } //生成原点 public static Point ORIGIN = new Point(); //计算一个坐标到原点的距离 public double distanceFromOrigin() { return Math.hypot(x, y); }
//计算两点间距离的静态方法,通过类名调用 //也可以通过实列对象调用啦,但根据江湖规矩还是用类名调用,不然别的程序员再维护你的代码时会痛骂你不讲武德。 public static double distance(Point p1, Point p2) { return Math.hypot(p1.x - p2.x, p1.y - p2.y); } //public中有main方法这段就不会调用,主要是可以调试在终端中java ./Ponit就可以运行Point类中的main方法 //甚至在java6以前可以不带main方法打印“Hello, World!”, 简直逆天!!! public static void main(String[] args) { Point p1 = new Point(3, 4); Point p2 = new Point(5, 9); System.out.println(distance(p1, p2)); } }
record PointInTime(double x, double y, Date when) {}
record Range(int from, int to) { //对于一个范围来说from 大于to不合理,用构造器合理化。 public Range { if (from > to) { int temp = from; from = to; to = temp; } } }
不过值得注意的是record中的字段一旦初始化以后就不能再修改 比如:
record Point(double x, double y){} //里面的相当于有如下实例字段的类 private final double x; private final double y;