Master Java’s Three Core OOP Features: Encapsulation, Inheritance, Polymorphism
This article explains Java’s three fundamental object‑oriented concepts—encapsulation, inheritance, and polymorphism—by defining each principle, showing concrete code examples, outlining key language keywords, and highlighting common pitfalls for beginners.
Introduction
Java is an object‑oriented programming language whose core ideas are built on three fundamental features: encapsulation, inheritance, and polymorphism.
1. Encapsulation
Encapsulation means wrapping data (fields) and operations (methods) inside a class, hiding implementation details and exposing only necessary interfaces.
public class BankAccount {
private String owner;
private double balance;
public BankAccount(String owner, double initialBalance) {
this.owner = owner;
this.balance = initialBalance;
}
public String getOwner() { return owner; }
public double getBalance() { return balance; }
public void deposit(double amount) {
if (amount <= 0) throw new IllegalArgumentException("存款金额必须大于 0");
balance += amount;
System.out.printf("存入 %.2f,余额:%.2f%n", amount, balance);
}
public void withdraw(double amount) {
if (amount > balance) throw new IllegalArgumentException("余额不足");
balance -= amount;
System.out.printf("取出 %.2f,余额:%.2f%n", amount, balance);
}
}
BankAccount acc = new BankAccount("张三", 1000);
acc.deposit(500); // 存入 500.00,余额:1500.00
acc.withdraw(200); // 取出 200.00,余额:1300.00
// acc.balance = 99999; // ❌ compile error, cannot modify directlyEncapsulation protects data integrity, reduces coupling, and makes maintenance easier.
2. Inheritance
Inheritance allows a subclass to reuse fields and methods of a parent class and to extend or override its behavior.
// Parent class
public class Animal {
protected String name;
public Animal(String name) { this.name = name; }
public void eat() { System.out.println(name + " 在吃东西"); }
public void sleep() { System.out.println(name + " 在睡觉"); }
}
// Subclass Dog
public class Dog extends Animal {
private String breed;
public Dog(String name, String breed) {
super(name);
this.breed = breed;
}
@Override
public void eat() {
System.out.println(name + "(" + breed + ")狼吞虎咽地吃东西");
}
public void bark() { System.out.println(name + ":汪汪汪!"); }
}
// Subclass Cat
public class Cat extends Animal {
public Cat(String name) { super(name); }
@Override
public void eat() { System.out.println(name + " 优雅地进食"); }
}Key inheritance keywords
extends: single inheritance in Java. super(): call parent constructor, must be first statement. super.method(): invoke a parent method. @Override: marks method overriding, compiler checks signature. protected: accessible to subclasses, not to external code. final class: class cannot be subclassed.
3. Polymorphism
Polymorphism lets a parent‑type reference point to a subclass object, and method calls are dispatched to the subclass implementation at runtime.
public class PolymorphismDemo {
public static void main(String[] args) {
Animal a1 = new Dog("旺财", "柴犬");
Animal a2 = new Cat("咪咪");
Animal a3 = new Dog("大黄", "拉布拉多");
Animal[] animals = {a1, a2, a3};
for (Animal animal : animals) {
animal.eat(); // runtime decides which eat() to call
}
// 旺财(柴犬)狼吞虎咽地吃东西
// 咪咪 优雅地进食
// 大黄(拉布拉多)狼吞虎咽地吃东西
if (a1 instanceof Dog dog) { // Java 16+ pattern matching
dog.bark(); // 旺财:汪汪汪!
}
}
}Prerequisites for polymorphism: There must be an inheritance or implementation relationship. The subclass overrides the parent method. A parent‑type reference points to a subclass instance.
4. Upcasting and Downcasting
Animal animal = new Dog("旺财", "柴犬"); // upcasting (automatic, safe)
// downcasting (requires explicit cast, may throw ClassCastException)
if (animal instanceof Dog) {
Dog dog = (Dog) animal; // safe cast
dog.bark();
}
// Java 16+ pattern matching (recommended)
if (animal instanceof Dog dog) {
dog.bark(); // concise
}5. Common Beginner Pitfalls
Constructor inheritance : constructors are not inherited; subclasses must explicitly call super().
Method overriding : overriding method cannot have more restrictive access and must return a compatible type.
Polymorphism limits : a parent reference can only invoke methods declared in the parent, not subclass‑specific methods.
Unsafe downcasting : always check with instanceof before casting to avoid ClassCastException.
6. Summary Cheat‑Sheet
Encapsulation → private fields + public methods, control access, protect data
Inheritance → extends reuse parent, super call, @Override for overriding
Polymorphism → parent reference → subclass, runtime dynamic binding, flexible codeThe three features form the skeleton of Java; without them frameworks like Spring and MyBatis would not exist.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
