Classes, Records, Fields, and Methods
Classes
A class is a blueprint for objects. It defines fields (state) and methods (behaviour):
javapublic class Person {
private String name;
private int age;
public String getName() { return name; }
public int getAge() { return age; }
}Access Modifiers
| Modifier | Accessible from |
|---|---|
private |
Same class only |
| (package) | Same package |
protected |
Same package + subclasses |
public |
Everywhere |
Fields
Instance fields belong to each object; static fields are shared across all instances:
javapublic class Counter {
private int count; // instance field
private static int total; // shared across all Counter objects
}Field defaults (when not explicitly initialised):
| Type | Default |
|---|---|
byte/short/int/long |
0 |
float/double |
0.0 |
boolean |
false |
char |
'' |
| Object reference | null |
Local variables have no default — they must be initialised before use.
Methods
javapublic double calculateArea(double radius) {
return Math.PI * radius * radius;
}- Return type must match the declared type (or be a subtype — covariant return).
- A
voidmethod may usereturn;with no value. staticmethods belong to the class and cannot access instance fields directly.
Method Signature
The signature is the method name + parameter types (not the return type):
javavoid process(int x) // signature: process(int)
void process(int x, int y) // signature: process(int, int) — overload
int process(int x) // SAME signature as first → compile errorRecords
A record is a concise, immutable data carrier (finalized in Java 16):
javapublic record Point(double x, double y) { }The compiler automatically generates:
private finalfields for each component- A canonical constructor
x()andy()accessor methodsequals(),hashCode(), andtoString()
javaPoint p = new Point(3.0, 4.0);
System.out.println(p.x()); // 3.0
System.out.println(p); // Point[x=3.0, y=4.0]Customising Records
javapublic record Range(int min, int max) {
// compact canonical constructor — validates without repeating assignments
Range {
if (min > max) throw new IllegalArgumentException("min > max");
}
// additional method
public int size() { return max - min; }
}Record Restrictions
- Fields are always
private final— cannot add instance fields. - Cannot extend another class (implicitly extends
Record). - Can implement interfaces.
- Can be generic.
Key Differences: Class vs Record
| Feature | Class | Record |
|---|---|---|
| Mutability | Mutable by default | Immutable (fields are final) |
| Boilerplate | Manual equals, hashCode, toString |
Auto-generated |
| Inheritance | Can extend classes | Cannot extend classes |
| Extra fields | Allowed | Not allowed (components only) |