Methods, classes and records
Static methods, overloading, classes with fields and constructors, and record for simple data.
Runs in Zerethon IDE · Java 25
Official Java documentation ↗
Main.java
public class Main {
record Point(int x, int y) {
double distance() {
return Math.sqrt(x * x + y * y);
}
}
static class Counter {
private int value;
Counter(int start) {
this.value = start;
}
int next() {
return ++value;
}
}
static int square(int x) {
return x * x;
}
static double square(double x) {
return x * x;
}
public static void main(String[] args) {
System.out.println(square(4) + " " + square(1.5));
Point p = new Point(3, 4);
System.out.println(p + " " + p.x() + " " + p.distance());
Counter c = new Counter(10);
c.next();
System.out.println(c.next());
}
}
Output
16 2.25 Point[x=3, y=4] 3 5.0 12
staticmethods belong to the class: call them frommainwithout creating an object.- A
recordgets a constructor, accessors (p.x()),equals,hashCodeandtoStringfor free. - Several top-level classes go in their own files (
Counter.javaforpublic class Counter); see “Packages and several files”.