Object-Oriented Programming in Java: Classes, Inheritance & Interfaces

Classes and objects, encapsulation with access modifiers, inheritance and polymorphism, abstract classes vs interfaces, and the modern record type — core OOP for backend Java.

BeginnerUpdated 2026-10-3087K views

Classes and Objects

public class User {
    // 字段(成员变量)
    private Long id;          // 封装:字段私有
    private String name;

    // 构造方法
    public User(Long id, String name) {
        this.id = id;
        this.name = name;
    }

    // getter / setter(Java 16+ 可用 record 简化)
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }

    // 方法重写 Object.toString
    @Override
    public String toString() {
        return "User{id=" + id + ", name='" + name + "'}";
    }
}

// 使用
User u = new User(1L, "Alice");
System.out.println(u.getName());

this refers to the current instance; new allocates an object on the heap; the default no-arg constructor exists only if you define no other constructor.

Encapsulation and Access Modifiers

ModifierClassPackageSubclassAnywhere
privateYesNoNoNo
default (package)YesYesNoNo
protectedYesYesYesNo
publicYesYesYesYes

Inheritance and Polymorphism

// 父类
class Animal {
    String name;
    Animal(String name) { this.name = name; }
    public String sound() { return "..."; }
}

// 子类用 extends 继承(Java 单继承)
class Dog extends Animal {
    Dog(String name) { super(name); }      // 调用父类构造
    @Override
    public String sound() { return "Woof"; }
}

// 多态:父类引用指向子类对象
Animal a = new Dog("Rex");
a.sound();                                // 输出 Woof — 动态分派

Polymorphism means the JVM decides which override to call based on the actual object type at runtime. instanceof pattern matching (Java 16+) makes type checks concise: if (a instanceof Dog d) d.sound();

Abstract Classes vs Interfaces

Use an abstract class when subclasses share state (fields) and common logic; use an interface to define a capability contract that any class can implement — a class can implement many interfaces but extend only one class. Since Java 8, interfaces can have default and static methods.

interface Comparable<T> {
    int compareTo(T other);
    default boolean lessThan(T other) {   // default 方法
        return compareTo(other) < 0;
    }
}

class Price implements Comparable<Price> {
    private final int cents;
    Price(int cents) { this.cents = cents; }
    @Override
    public int compareTo(Price o) { return Integer.compare(cents, o.cents); }
}

Modern Java: record and sealed

// record:不可变数据载体(Java 16+)
// 自动生成构造、getter、equals、hashCode、toString
public record Point(int x, int y) {}

Point p = new Point(3, 4);
p.x();                  // 3

// sealed:限制继承层级(Java 17+)
public sealed abstract class Shape permits Circle, Square {}
final class Circle extends Shape { double r; }
final class Square extends Shape { double side; }

Friends & Partners