Lesson 286 of 296
Java object-oriented programming
What you will learn
- Classes, fields, constructors and this
- Access modifiers and encapsulation
- static and final
- Inheritance, abstract classes and polymorphism
- Interfaces
- Records and enums
- equals, hashCode and toString
On this page
Classes and constructors
public class Account {
private final String owner; // private: only this class can see it
private double balance; // final: can be set only once
public Account(String owner, double balance) { // constructor
this.owner = owner;
this.balance = balance;
}
public Account(String owner) { // overloaded constructor
this(owner, 0);
}
public void deposit(double amount) {
if (amount <= 0) throw new IllegalArgumentException("Amount must be positive");
balance += amount;
}
public double getBalance() { return balance; } // a "getter"
public String getOwner() { return owner; }
public static void main(String[] args) {
Account a = new Account("Sam");
a.deposit(50);
System.out.println(a.getOwner() + " " + a.getBalance()); // Sam 50.0
}
}Access modifiers and encapsulation
| Modifier | Who can access |
|---|---|
| public | Everyone |
| protected | Same package and subclasses |
| (none, "package-private") | Same package only |
| private | This class only |
Encapsulation: keep fields private and allow changes only through methods that protect the rules (like deposit rejecting negative amounts). Unlike TypeScript, private is enforced at runtime too.
static and final
- static belongs to the class, not to each object:
Math.max(...), a shared counter, a factory method. - final variable: cannot be reassigned (like
const). final method: cannot be overridden. final class: cannot be extended (Stringis final).
Inheritance, abstract classes and polymorphism
public class Shapes {
public static void main(String[] args) {
Shape[] shapes = { new Circle(1), new Square(2) };
for (Shape s : shapes) {
System.out.println(s.describe()); // polymorphism: each uses its own area()
}
}
}
abstract class Shape { // cannot be created directly
abstract double area(); // subclasses must implement it
String describe() {
return getClass().getSimpleName() + " with area " + String.format("%.2f", area());
}
}
class Circle extends Shape {
private final double r;
Circle(double r) { this.r = r; }
@Override double area() { return Math.PI * r * r; }
}
class Square extends Shape {
private final double side;
Square(double side) { this.side = side; }
@Override double area() { return side * side; }
}extends: a class can extend only one class.@Overrideasks the compiler to check you really are overriding a parent method.super(...)calls the parent constructor;super.method()calls the parent's version.- Polymorphism: a
Shapevariable can hold aCircleorSquare, and the rightarea()runs.
Interfaces
An interface is a contract. A class can implement many interfaces. Unlike TypeScript (structural typing), Java uses nominal typing: a class must say implements explicitly, even if it has the right methods.
public class Interfaces {
public static void main(String[] args) {
Invoice inv = new Invoice(120.0);
Payable p = inv; // program to the interface
System.out.println(p.summary()); // Due: 120.0
System.out.println(inv.print()); // Invoice for 120.0
}
}
interface Payable {
double amountDue();
default String summary() { // default method: shared implementation
return "Due: " + amountDue();
}
}
interface Printable {
String print();
}
class Invoice implements Payable, Printable {
private final double total;
Invoice(double total) { this.total = total; }
public double amountDue() { return total; }
public String print() { return "Invoice for " + total; }
}| Abstract class | Interface |
|---|---|
| Can have fields with state and constructors | No instance state (constants only) |
| A class extends only one | A class can implement many |
| Use for a shared base with shared code | Use for a capability or contract |
Records and enums
A record (Java 16+) is a short, immutable data class. Java writes the constructor, getters, equals, hashCode and toString for you.
public class RecordsEnums {
public static void main(String[] args) {
Point a = new Point(1, 2);
System.out.println(a); // Point[x=1, y=2]
System.out.println(a.x()); // 1 (accessor, not getX())
System.out.println(a.equals(new Point(1, 2))); // true
System.out.println(Status.PAID.isDone()); // false
System.out.println(Status.valueOf("SHIPPED").ordinal()); // 2
}
}
record Point(int x, int y) {
Point { // compact constructor for validation
if (x < 0 || y < 0) throw new IllegalArgumentException("negative");
}
}
enum Status {
PENDING, PAID, SHIPPED;
boolean isDone() { return this == SHIPPED; }
}equals, hashCode and toString
Every class extends Object, which has:
toString(): the text form. Override it for readable logs.equals(Object o): are two objects equal in value? By default it checks if they are the same object.hashCode(): a number used byHashMapandHashSetto find objects quickly.
The rule: if you override equals, you must override hashCode, so that equal objects have equal hash codes. Otherwise HashMap and HashSet break.
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;
public class Equality {
public static void main(String[] args) {
Set<Email> emails = new HashSet<>();
emails.add(new Email("Sam@Example.com"));
emails.add(new Email("sam@example.com"));
System.out.println(emails.size()); // 1, because equals and hashCode agree
}
}
class Email {
private final String value;
Email(String value) { this.value = value.toLowerCase(); }
@Override public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Email other)) return false; // pattern matching instanceof
return value.equals(other.value);
}
@Override public int hashCode() { return Objects.hash(value); }
@Override public String toString() { return value; }
}Records do this for you, which is one reason to prefer them for data.
How to say it in an interview
"I keep fields private and change them through methods that protect the rules. static belongs to the class, final prevents reassignment, overriding or extending. A class extends one class but implements many interfaces, and Java uses nominal typing, so implements must be explicit. I use abstract classes for a shared base with code, interfaces for contracts, records for immutable data and enums for fixed sets of values. If I override equals I always override hashCode, or hash-based collections break."
Key words
| Word | Meaning |
|---|---|
| Constructor | Code that runs when an object is created with new |
| Encapsulation | Hiding fields and exposing safe methods |
| static | Belongs to the class, not each object |
| final | Cannot be reassigned, overridden or extended |
| Polymorphism | One type of variable, different behaviour per subclass |
| Interface | A contract a class promises to fulfil |
| Record | A short immutable data class |
| hashCode | A number used to find objects in hash-based collections |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.