Java OOP Cheat Sheet
Classes, constructors, inheritance, interfaces, records, enums, exceptions, and generics.
Updated
Classes and objects#
public class Account {
private final String owner; // fields: private, final when possible
private double balance;
public Account(String owner) { // constructor: no return type
this.owner = owner;
}
public void deposit(double amount) { // instance method
if (amount <= 0) throw new IllegalArgumentException("must be positive");
balance += amount;
}
public double getBalance() { return balance; }
@Override
public String toString() { return owner + ": " + balance; }
}
Account a = new Account("Asha");
a.deposit(500);
System.out.println(a); // calls toString()Constructors#
class Timer {
private final int seconds;
Timer(int minutes, int seconds) { this.seconds = minutes * 60 + seconds; }
Timer(int seconds) { this(0, seconds); } // delegate: must be first
Timer() { this(0); }
}Writing any constructor removes the default no-argument constructor.
static#
class Counter {
static int created = 0; // one copy shared by the class
Counter() { created++; }
static int count() { return created; } // call as Counter.count()
}Inheritance#
class Employee {
protected final String name;
Employee(String name) { this.name = name; }
double pay() { return 50000; }
}
class Manager extends Employee { // one superclass only
Manager(String name) { super(name); } // super(...) first
@Override
double pay() { return super.pay() + 15000; }
}
Employee e = new Manager("Meera"); // upcast
e.pay(); // 65000.0: chosen at run time
if (e instanceof Manager m) { } // pattern matching (Java 16+)Every class extends Object (toString, equals, hashCode). Override equals and hashCode together.
Abstract classes and interfaces#
abstract class Shape {
abstract double area(); // no body
String describe() { return "area " + area(); }
}
interface Payment {
boolean pay(double amount); // public abstract
default String currency() { return "INR"; } // default method
static Payment free() { return amount -> true; }
}
class Card implements Payment, Comparable<Card> { // many interfaces
public boolean pay(double amount) { return amount < 50000; }
public int compareTo(Card other) { return 0; }
}
@FunctionalInterface
interface Operation { double apply(double a, double b); }
Operation add = (a, b) -> a + b; // lambda implements itRecords, enums and sealed types#
record Point(int x, int y) { // final fields, constructor,
Point { // accessors x(), y(), equals,
if (x < 0) throw new IllegalArgumentException(); // hashCode, toString
}
}
enum Size {
SMALL(100), LARGE(200);
private final int price;
Size(int price) { this.price = price; }
int price() { return price; }
}
// Size.valueOf("SMALL") gives SMALL; Size.values() gives every constant
sealed interface Shape2 permits Circle, Square {}
record Circle(double r) implements Shape2 {}
record Square(double s) implements Shape2 {}
double area = switch (shape) { // exhaustive, no default needed
case Circle(double r) -> Math.PI * r * r;
case Square(double s) -> s * s;
};Exceptions#
try {
int n = Integer.parseInt(text);
} catch (NumberFormatException e) { // specific first
System.out.println(e.getMessage());
} catch (RuntimeException e) {
throw e; // rethrow
} finally {
// always runs
}
try (BufferedReader r = Files.newBufferedReader(path)) { // closed automatically
String line = r.readLine();
}
String read(Path p) throws IOException { return Files.readString(p); } // checked: declare
class InsufficientFunds extends RuntimeException { // custom (unchecked)
InsufficientFunds(String msg) { super(msg); }
}Generics#
class Box<T> {
private final T value;
Box(T value) { this.value = value; }
T get() { return value; }
}
static <T extends Comparable<T>> T max(List<T> items) { return items.get(0); }
double sum(List<? extends Number> nums) { return 0; } // read from: extends
void fill(List<? super Integer> out) { out.add(1); } // write to: superLambdas and method references#
Predicate<String> empty = String::isEmpty;
Function<String, Integer> length = s -> s.length();
Consumer<String> print = System.out::println;
Supplier<List<String>> make = ArrayList::new;
BiFunction<Integer, Integer, Integer> add = Integer::sum;Lambdas may only use local variables that are effectively final.
Want the full explanations? Go to the Learn Java course →