0

[Java Backend Zero to Hello] BÀI 1.7: 4 TÍNH CHẤT CỦA OOP

Java Backend Zero to Hello

📚 Bài viết thuộc series Java Backend Zero to Hello 📌 Phần: Phase 1: Java Core Cơ Bản | Bài 9/86


BÀI 1.7: 4 TÍNH CHẤT CỦA OOP

Mục tiêu

  • Nắm vững 4 tính chất: Encapsulation, Inheritance, Polymorphism, Abstraction
  • Áp dụng vào thiết kế class thực tế
  • Hiểu khi nào dùng tính chất nào

1. ENCAPSULATION (ĐÓNG GÓI)

Định nghĩa: Che giấu chi tiết triển khai, chỉ cung cấp giao diện cần thiết.

1.1 Triển khai

  • Dùng private cho fields
  • Cung cấp public getter/setter
  • Validate dữ liệu trong setter

1.2 Ví dụ

public class BankAccount {
    private String accountNumber;
    private double balance;
    private String pin;

    public BankAccount(String accountNumber, String pin) {
        this.accountNumber = accountNumber;
        this.pin = pin;
        this.balance = 0;
    }

    public void deposit(double amount) {
        if (amount <= 0) {
            throw new IllegalArgumentException("Số tiền phải > 0");
        }
        balance += amount;
    }

    public boolean withdraw(double amount, String pin) {
        if (!this.pin.equals(pin)) {
            System.out.println("Sai mã PIN");
            return false;
        }
        if (amount > balance) {
            System.out.println("Số dư không đủ");
            return false;
        }
        balance -= amount;
        return true;
    }

    public double getBalance() {
        return balance;
    }

    // Không có setter cho balance - chỉ thay đổi qua deposit/withdraw
}

1.3 Lợi ích

  • Bảo vệ tính toàn vẹn dữ liệu
  • Linh hoạt thay đổi implementation
  • Giảm coupling giữa các class

2. INHERITANCE (KẾ THỪA)

Định nghĩa: Class con thừa hưởng thuộc tính và phương thức từ class cha.

2.1 Cú pháp

public class ChildClass extends ParentClass {
    // Thêm field/method mới
    // Override method cha
}

2.2 Ví dụ

// Class cha
public class Animal {
    protected String name;
    protected int age;

    public Animal(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public void eat() {
        System.out.println(name + " đang ăn");
    }

    public void sleep() {
        System.out.println(name + " đang ngủ");
    }

    public void makeSound() {
        System.out.println("...");
    }
}

// Class con
public class Dog extends Animal {
    private String breed;

    public Dog(String name, int age, String breed) {
        super(name, age);  // Gọi constructor cha
        this.breed = breed;
    }

    @Override
    public void makeSound() {
        System.out.println(name + " sủa: Gâu gâu!");
    }

    public void fetch() {
        System.out.println(name + " đang nhặt bóng");
    }
}

public class Cat extends Animal {
    public Cat(String name, int age) {
        super(name, age);
    }

    @Override
    public void makeSound() {
        System.out.println(name + " kêu: Meo meo!");
    }
}

2.3 Từ khóa super

public class Dog extends Animal {
    public Dog(String name, int age) {
        super(name, age);  // Gọi constructor cha
    }

    @Override
    public void eat() {
        super.eat();  // Gọi method cha
        System.out.println("Xong rồi!");
    }
}

2.4 Các kiểu kế thừa trong Java

Java không hỗ trợ đa kế thừa (multiple inheritance) với class.

✅ Single:        A → B
✅ Multilevel:    A → B → C
✅ Hierarchical:  A → B, A → C
❌ Multiple:      A, B → C (chỉ hỗ trợ qua interface)

2.5 Method Overriding (Ghi đè)

public class Parent {
    public void display() {
        System.out.println("Parent display");
    }
}

public class Child extends Parent {
    @Override  // Annotation - kiểm tra override đúng
    public void display() {
        System.out.println("Child display");
    }
}

Quy tắc override:

  • Cùng tên, cùng tham số, cùng kiểu trả về (hoặc covariant)
  • Access modifier không được hẹp hơn
  • Không override static, final, private

3. POLYMORPHISM (ĐA HÌNH)

Định nghĩa: Cùng một hành động nhưng có nhiều cách thực hiện khác nhau.

3.1 Polymorphism qua kế thừa

Animal animal1 = new Dog("Buddy", 3, "Husky");
Animal animal2 = new Cat("Whiskers", 2);

animal1.makeSound();  // Buddy sủa: Gâu gâu!
animal2.makeSound();  // Whiskers kêu: Meo meo!

3.2 Upcasting và Downcasting

// Upcasting (tự động) - an toàn
Animal animal = new Dog("Buddy", 3, "Husky");

// Downcasting (thủ công) - cần kiểm tra
if (animal instanceof Dog) {
    Dog dog = (Dog) animal;
    dog.fetch();
}

// Pattern matching (Java 16+)
if (animal instanceof Dog dog) {
    dog.fetch();
}

3.3 Polymorphism với tham số

public class Zoo {
    public void makeAnimalSound(Animal animal) {
        animal.makeSound();  // Gọi method phù hợp với object thực tế
    }
}

Zoo zoo = new Zoo();
zoo.makeAnimalSound(new Dog("Buddy", 3, "Husky"));  // Gâu gâu!
zoo.makeAnimalSound(new Cat("Whiskers", 2));         // Meo meo!

3.4 Lợi ích

  • Code linh hoạt, dễ mở rộng
  • Giảm coupling
  • Dễ bảo trì

4. ABSTRACTION (TRỪU TƯỢNG)

Định nghĩa: Ẩn chi tiết triển khai, chỉ hiển thị tính năng.

4.1 Abstract Class

public abstract class Shape {
    protected String color;

    public Shape(String color) {
        this.color = color;
    }

    // Abstract method - không có thân
    public abstract double area();
    public abstract double perimeter();

    // Method thường
    public String getColor() {
        return color;
    }
}

public class Circle extends Shape {
    private double radius;

    public Circle(String color, double radius) {
        super(color);
        this.radius = radius;
    }

    @Override
    public double area() {
        return Math.PI * radius * radius;
    }

    @Override
    public double perimeter() {
        return 2 * Math.PI * radius;
    }
}

public class Rectangle extends Shape {
    private double width, height;

    public Rectangle(String color, double width, double height) {
        super(color);
        this.width = width;
        this.height = height;
    }

    @Override
    public double area() {
        return width * height;
    }

    @Override
    public double perimeter() {
        return 2 * (width + height);
    }
}

4.2 Đặc điểm Abstract Class

  • Không thể tạo object trực tiếp: new Shape() ❌
  • Có thể có abstract method và method thường
  • Có thể có constructor (gọi qua super)
  • Có thể có field
  • Class con phải override tất cả abstract method (hoặc cũng khai báo abstract)

4.3 Interface (sẽ học chi tiết ở bài 1.8)

public interface Drawable {
    void draw();  // Mặc định là public abstract
}

public interface Movable {
    void move(int x, int y);
}

public class Circle extends Shape implements Drawable, Movable {
    @Override
    public void draw() {
        System.out.println("Vẽ hình tròn");
    }

    @Override
    public void move(int x, int y) {
        System.out.println("Di chuyển đến " + x + "," + y);
    }
}

5. SO SÁNH CÁC TÍNH CHẤT

Tính chất Mục đích Công cụ
Encapsulation Ẩn dữ liệu private, getter/setter
Inheritance Tái sử dụng code extends
Polymorphism Linh hoạt hành vi Overriding, Overloading
Abstraction Ẩn chi tiết abstract class, interface

6. OBJECT CLASS

Mọi class trong Java đều kế thừa từ Object.

Các method quan trọng

public class User {
    private String name;
    private int age;

    // toString - biểu diễn chuỗi
    @Override
    public String toString() {
        return "User{name=" + name + ", age=" + age + "}";
    }

    // equals - so sánh bằng
    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        User user = (User) o;
        return age == user.age && Objects.equals(name, user.name);
    }

    // hashCode - mã băm
    @Override
    public int hashCode() {
        return Objects.hash(name, age);
    }
}

💡 Khi override equals(), phải override hashCode().


7. BÀI TẬP THỰC HÀNH

Bài 1: Hệ thống nhân viên

Employee (abstract)
├── name, salary
├── abstract calculateBonus()
└── getDetails()

FullTimeEmployee extends Employee
└── calculateBonus() = salary * 0.1

PartTimeEmployee extends Employee
├── hoursWorked, hourlyRate
└── calculateBonus() = hoursWorked * hourlyRate * 0.05

Bài 2: Hệ thống hình học

Shape (abstract)
├── color
├── abstract area()
└── abstract perimeter()

Circle, Rectangle, Triangle extends Shape

Bài 3: Hệ thống ngân hàng

Account (abstract)
├── accountNumber, balance
├── abstract calculateInterest()
├── deposit(), withdraw()

SavingsAccount extends Account
└── calculateInterest() = balance * 0.05

CheckingAccount extends Account
└── calculateInterest() = balance * 0.01

Bài 4: Override toString, equals, hashCode

Cho class Product(id, name, price).


8. TÓM TẮT

Tính chất Từ khóa Đặc điểm
Encapsulation private, getter/setter Ẩn dữ liệu
Inheritance extends, super Tái sử dụng code
Polymorphism Overriding, Overloading Cùng hành động, nhiều cách
Abstraction abstract, interface Ẩn chi tiết

Bài tiếp theo: 1.8 Abstract class & Interface


🧭 Điều Hướng Series

⬅️ Bài trước: BÀI 1.6: LẬP TRÌNH HƯỚNG ĐỐI TƯỢNG (OOP) - CƠ BẢN

📋 Lộ trình tổng quan: Xem Toàn Bộ Series

➡️ Bài tiếp theo: BÀI 1.8: ABSTRACT CLASS & INTERFACE


All Rights Reserved

Viblo
Let's register a Viblo Account to get more interesting posts.