Kế Thừa trong Java 🧬
🎯 Mục tiêu: Học cách sử dụng kế thừa để tái sử dụng code và tạo các lớp có mối quan hệ phân cấp trong Java.
Giới thiệu 📝
Kế thừa (Inheritance) là một trong những tính năng cốt lõi của lập trình hướng đối tượng, cho phép một lớp (lớp con) kế thừa các thuộc tính và phương thức từ một lớp khác (lớp cha). Trong Java, kế thừa được thực hiện thông qua từ khóa extends
.
💡 Fun Fact: Kế thừa giúp chúng ta tái sử dụng code hiệu quả, giảm thiểu việc lặp lại code và tạo ra các lớp có mối quan hệ logic với nhau.
1. Cú Pháp Cơ Bản ⚡
Kế Thừa Đơn Giản
// Lớp cha
public class Animal {
protected String name;
protected int age;
public Animal(String name, int age) {
this.name = name;
this.age = age;
}
public void makeSound() {
System.out.println("Some sound");
}
}
// Lớp con
public class Dog extends Animal {
private String breed;
public Dog(String name, int age, String breed) {
super(name, age); // Gọi constructor của lớp cha
this.breed = breed;
}
@Override
public void makeSound() {
System.out.println("Woof!");
}
}
Kế Thừa với Nhiều Thuộc Tính
public class Vehicle {
protected String brand;
protected String model;
protected int year;
public Vehicle(String brand, String model, int year) {
this.brand = brand;
this.model = model;
this.year = year;
}
public void start() {
System.out.println("Starting vehicle");
}
}
public class Car extends Vehicle {
private int numberOfDoors;
public Car(String brand, String model, int year, int numberOfDoors) {
super(brand, model, year);
this.numberOfDoors = numberOfDoors;
}
@Override
public void start() {
System.out.println("Starting car");
}
}
2. Các Loại Kế Thừa 🔄
Kế Thừa Đơn
public class Person {
protected String name;
protected int age;
}
public class Student extends Person {
private String studentId;
}
Kế Thừa Nhiều Cấp
public class Animal {
protected String name;
}
public class Mammal extends Animal {
protected boolean hasFur;
}
public class Dog extends Mammal {
private String breed;
}
Kế Thừa Phân Cấp
public class Shape {
protected double area;
}
public class Circle extends Shape {
private double radius;
}
public class Rectangle extends Shape {
private double length;
private double width;
}
3. Truy Cập Thành Viên 🔐
Truy Cập Từ Lớp Con
public class Parent {
private String privateField;
protected String protectedField;
public String publicField;
private void privateMethod() { }
protected void protectedMethod() { }
public void publicMethod() { }
}
public class Child extends Parent {
public void accessMembers() {
// privateField không thể truy cập
protectedField = "Accessible"; // Có thể truy cập
publicField = "Accessible"; // Có thể truy cập
// privateMethod() không thể gọi
protectedMethod(); // Có thể gọi
publicMethod(); // Có thể gọi
}
}
4. Ghi Đè Phương Thức 🎯
Ghi Đè Cơ Bản
public class Animal {
public void makeSound() {
System.out.println("Some sound");
}
}
public class Dog extends Animal {
@Override
public void makeSound() {
System.out.println("Woof!");
}
}
Ghi Đè với Super
public class Vehicle {
public void start() {
System.out.println("Starting vehicle");
}
}
public class Car extends Vehicle {
@Override
public void start() {
super.start(); // Gọi phương thức của lớp cha
System.out.println("Starting car engine");
}
}
5. Ví Dụ Thực Tế 🚀
Quản Lý Nhân Viên
public class Employee {
protected String name;
protected int id;
protected double salary;
public Employee(String name, int id, double salary) {
this.name = name;
this.id = id;
this.salary = salary;
}
public void displayInfo() {
System.out.println("Name: " + name);
System.out.println("ID: " + id);
System.out.println("Salary: " + salary);
}
}
public class Manager extends Employee {
private String department;
public Manager(String name, int id, double salary, String department) {
super(name, id, salary);
this.department = department;
}
@Override
public void displayInfo() {
super.displayInfo();
System.out.println("Department: " + department);
}
public void manageTeam() {
System.out.println("Managing team in " + department);
}
}
Quản Lý Phương Tiện
public class Vehicle {
protected String brand;
protected String model;
protected int year;
protected double fuelLevel;
public Vehicle(String brand, String model, int year) {
this.brand = brand;
this.model = model;
this.year = year;
this.fuelLevel = 100.0;
}
public void start() {
System.out.println("Starting vehicle");
}
public void refuel() {
fuelLevel = 100.0;
System.out.println("Vehicle refueled");
}
}
public class Car extends Vehicle {
private int numberOfDoors;
public Car(String brand, String model, int year, int numberOfDoors) {
super(brand, model, year);
this.numberOfDoors = numberOfDoors;
}
@Override
public void start() {
System.out.println("Starting car engine");
}
public void openDoors() {
System.out.println("Opening " + numberOfDoors + " doors");
}
}
Quản Lý Sản Phẩm
public class Product {
protected String name;
protected double price;
protected int stock;
public Product(String name, double price, int stock) {
this.name = name;
this.price = price;
this.stock = stock;
}
public void displayInfo() {
System.out.println("Product: " + name);
System.out.println("Price: $" + price);
System.out.println("Stock: " + stock);
}
}
public class Electronics extends Product {
private String warranty;
public Electronics(String name, double price, int stock, String warranty) {
super(name, price, stock);
this.warranty = warranty;
}
@Override
public void displayInfo() {
super.displayInfo();
System.out.println("Warranty: " + warranty);
}
public void checkWarranty() {
System.out.println("Checking warranty status for " + name);
}
}
6. Best Practices ✅
-
Sử Dụng Protected Cho Các Thành Viên Cần Kế Thừa
// Không nên
private String name; // Lớp con không thể truy cập
// Nên
protected String name; // Lớp con có thể truy cập -
Gọi Super Constructor
// Không nên
public Child() {
// Quên gọi super()
}
// Nên
public Child() {
super();
} -
Sử Dụng @Override
// Không nên
public void makeSound() {
System.out.println("Woof!");
}
// Nên
@Override
public void makeSound() {
System.out.println("Woof!");
}
7. Lỗi Thường Gặp ⚠️
-
Quên Gọi Super Constructor
// Lỗi
public class Child extends Parent {
public Child() {
// Quên gọi super()
}
}
// Đúng
public class Child extends Parent {
public Child() {
super();
}
} -
Truy Cập Private Members
// Lỗi
public class Child extends Parent {
public void accessPrivate() {
privateField = "Error"; // Không thể truy cập
}
}
// Đúng
public class Child extends Parent {
public void accessProtected() {
protectedField = "OK"; // Có thể truy cập
}
} -
Quên @Override
// Lỗi
public class Child extends Parent {
public void makeSound() { // Quên @Override
System.out.println("Woof!");
}
}
// Đúng
public class Child extends Parent {
@Override
public void makeSound() {
System.out.println("Woof!");
}
}
8. Ví Dụ Thực Tế Nâng Cao 🎯
Quản Lý Hệ Thống Giáo Dục
public class Person {
protected String name;
protected int age;
protected String address;
public Person(String name, int age, String address) {
this.name = name;
this.age = age;
this.address = address;
}
public void displayInfo() {
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Address: " + address);
}
}
public class Student extends Person {
private String studentId;
private String major;
private double gpa;
public Student(String name, int age, String address,
String studentId, String major) {
super(name, age, address);
this.studentId = studentId;
this.major = major;
this.gpa = 0.0;
}
@Override
public void displayInfo() {
super.displayInfo();
System.out.println("Student ID: " + studentId);
System.out.println("Major: " + major);
System.out.println("GPA: " + gpa);
}
public void updateGPA(double newGPA) {
this.gpa = newGPA;
System.out.println("GPA updated to: " + newGPA);
}
}
public class Teacher extends Person {
private String department;
private String specialization;
private List<String> courses;
public Teacher(String name, int age, String address,
String department, String specialization) {
super(name, age, address);
this.department = department;
this.specialization = specialization;
this.courses = new ArrayList<>();
}
@Override
public void displayInfo() {
super.displayInfo();
System.out.println("Department: " + department);
System.out.println("Specialization: " + specialization);
System.out.println("Courses: " + courses);
}
public void addCourse(String course) {
courses.add(course);
System.out.println("Added course: " + course);
}
}
Quản Lý Hệ Thống Ngân Hàng
public class Account {
protected String accountNumber;
protected String accountHolder;
protected double balance;
public Account(String accountNumber, String accountHolder) {
this.accountNumber = accountNumber;
this.accountHolder = accountHolder;
this.balance = 0.0;
}
public void deposit(double amount) {
balance += amount;
System.out.println("Deposited: $" + amount);
}
public void withdraw(double amount) {
if (amount <= balance) {
balance -= amount;
System.out.println("Withdrawn: $" + amount);
} else {
System.out.println("Insufficient funds");
}
}
}
public class SavingsAccount extends Account {
private double interestRate;
public SavingsAccount(String accountNumber, String accountHolder,
double interestRate) {
super(accountNumber, accountHolder);
this.interestRate = interestRate;
}
public void addInterest() {
double interest = balance * interestRate;
deposit(interest);
System.out.println("Added interest: $" + interest);
}
}
public class CheckingAccount extends Account {
private double overdraftLimit;
public CheckingAccount(String accountNumber, String accountHolder,
double overdraftLimit) {
super(accountNumber, accountHolder);
this.overdraftLimit = overdraftLimit;
}
@Override
public void withdraw(double amount) {
if (amount <= (balance + overdraftLimit)) {
balance -= amount;
System.out.println("Withdrawn: $" + amount);
} else {
System.out.println("Exceeds overdraft limit");
}
}
}
💡 Lời khuyên: Hãy thực hành với các ví dụ thực tế để hiểu rõ hơn về cách sử dụng kế thừa trong các tình huống khác nhau.
Tiếp Theo 🎯
Trong các bài học tiếp theo, chúng ta sẽ:
- Tìm hiểu về abstract classes
- Học cách sử dụng interfaces
- Thực hành với các ví dụ thực tế
- Tìm hiểu về polymorphism