Java面向对象

Java 面向对象编程详解

1. 面向对象基本概念

三大特性:

  • 封装:隐藏实现细节,提供公共访问方式

  • 继承:子类继承父类的特征和行为

  • 多态:同一操作作用于不同对象,产生不同结果

2. 类与对象

类的定义

// 学生类
public class Student {
    // 属性(成员变量)
    private String name;
    private int age;
    private String studentId;
    
    // 构造方法
    public Student() {
        // 默认构造方法
    }
    
    // 带参数的构造方法
    public Student(String name, int age, String studentId) {
        this.name = name;
        this.age = age;
        this.studentId = studentId;
    }
    
    // 方法(成员方法)
    public void study() {
        System.out.println(name + "正在学习...");
    }
    
    public void displayInfo() {
        System.out.println("学生信息:");
        System.out.println("姓名:" + name);
        System.out.println("年龄:" + age);
        System.out.println("学号:" + studentId);
    }
    
    // Getter和Setter方法(封装)
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    
    public int getAge() {
        return age;
    }
    
    public void setAge(int age) {
        if (age > 0 && age < 150) {
            this.age = age;
        } else {
            System.out.println("年龄不合法!");
        }
    }
    
    public String getStudentId() {
        return studentId;
    }
    
    public void setStudentId(String studentId) {
        this.studentId = studentId;
    }
}

对象创建和使用

public class ObjectExample {
    public static void main(String[] args) {
        // 创建对象
        Student student1 = new Student(); // 使用默认构造方法
        student1.setName("张三");
        student1.setAge(20);
        student1.setStudentId("2023001");
        
        Student student2 = new Student("李四", 22, "2023002"); // 使用带参构造方法
        
        // 使用对象方法
        student1.study();
        student1.displayInfo();
        
        student2.study();
        student2.displayInfo();
        
        // 对象数组
        Student[] students = new Student[3];
        students[0] = student1;
        students[1] = student2;
        students[2] = new Student("王五", 21, "2023003");
        
        System.out.println("\n所有学生信息:");
        for (Student student : students) {
            student.displayInfo();
            System.out.println("---------");
        }
    }
}

3. 封装

public class BankAccount {
    // 私有属性(封装)
    private String accountNumber;
    private String accountHolder;
    private double balance;
    private String password;
    
    // 构造方法
    public BankAccount(String accountNumber, String accountHolder, double initialBalance, String password) {
        this.accountNumber = accountNumber;
        this.accountHolder = accountHolder;
        this.balance = initialBalance;
        this.password = password;
    }
    
    // 公共方法访问私有属性
    public boolean deposit(double amount) {
        if (amount > 0) {
            balance += amount;
            System.out.println("存款成功!当前余额:" + balance);
            return true;
        }
        System.out.println("存款金额必须大于0!");
        return false;
    }
    
    public boolean withdraw(double amount, String inputPassword) {
        if (!verifyPassword(inputPassword)) {
            System.out.println("密码错误!");
            return false;
        }
        
        if (amount > 0 && amount <= balance) {
            balance -= amount;
            System.out.println("取款成功!当前余额:" + balance);
            return true;
        }
        System.out.println("取款失败!余额不足或金额不合法。");
        return false;
    }
    
    public void checkBalance(String inputPassword) {
        if (verifyPassword(inputPassword)) {
            System.out.println("当前余额:" + balance);
        } else {
            System.out.println("密码错误!");
        }
    }
    
    // 私有方法(内部使用)
    private boolean verifyPassword(String inputPassword) {
        return this.password.equals(inputPassword);
    }
    
    // Getter方法
    public String getAccountNumber() {
        return accountNumber;
    }
    
    public String getAccountHolder() {
        return accountHolder;
    }
    
    // 没有提供balance的getter,通过方法控制访问
}

4. 继承

父类(基类)

// 人类(父类)
public class Person {
    protected String name;
    protected int age;
    protected String gender;
    
    public Person(String name, int age, String gender) {
        this.name = name;
        this.age = age;
        this.gender = gender;
    }
    
    public void eat() {
        System.out.println(name + "正在吃饭...");
    }
    
    public void sleep() {
        System.out.println(name + "正在睡觉...");
    }
    
    public void introduce() {
        System.out.println("我叫" + name + ",今年" + age + "岁,性别:" + gender);
    }
    
    // Getter和Setter
    public String getName() {
        return name;
    }
    
    public void setName(String name) {
        this.name = name;
    }
    
    public int getAge() {
        return age;
    }
    
    public void setAge(int age) {
        this.age = age;
    }
    
    public String getGender() {
        return gender;
    }
    
    public void setGender(String gender) {
        this.gender = gender;
    }
}

子类

// 学生类(继承人类)
public class CollegeStudent extends Person {
    private String major;
    private String studentId;
    private double gpa;
    
    public CollegeStudent(String name, int age, String gender, String major, String studentId) {
        super(name, age, gender); // 调用父类构造方法
        this.major = major;
        this.studentId = studentId;
        this.gpa = 0.0;
    }
    
    // 学生特有的方法
    public void study() {
        System.out.println(name + "正在学习" + major + "专业...");
    }
    
    public void takeExam() {
        System.out.println(name + "正在参加考试...");
    }
    
    // 重写父类方法
    @Override
    public void introduce() {
        super.introduce(); // 调用父类方法
        System.out.println("我是" + major + "专业的学生,学号:" + studentId);
    }
    
    // Getter和Setter
    public String getMajor() {
        return major;
    }
    
    public void setMajor(String major) {
        this.major = major;
    }
    
    public String getStudentId() {
        return studentId;
    }
    
    public void setStudentId(String studentId) {
        this.studentId = studentId;
    }
    
    public double getGpa() {
        return gpa;
    }
    
    public void setGpa(double gpa) {
        if (gpa >= 0.0 && gpa <= 4.0) {
            this.gpa = gpa;
        }
    }
}
// 教师类(继承人类)
public class Teacher extends Person {
    private String department;
    private String employeeId;
    private String title;
    
    public Teacher(String name, int age, String gender, String department, String employeeId, String title) {
        super(name, age, gender);
        this.department = department;
        this.employeeId = employeeId;
        this.title = title;
    }
    
    // 教师特有的方法
    public void teach() {
        System.out.println(title + name + "正在授课...");
    }
    
    public void gradePapers() {
        System.out.println(name + "正在批改作业...");
    }
    
    // 重写父类方法
    @Override
    public void introduce() {
        super.introduce();
        System.out.println("我是" + department + "的" + title + ",工号:" + employeeId);
    }
    
    // Getter和Setter
    public String getDepartment() {
        return department;
    }
    
    public void setDepartment(String department) {
        this.department = department;
    }
    
    public String getEmployeeId() {
        return employeeId;
    }
    
    public void setEmployeeId(String employeeId) {
        this.employeeId = employeeId;
    }
    
    public String getTitle() {
        return title;
    }
    
    public void setTitle(String title) {
        this.title = title;
    }
}

5. 多态

public class PolymorphismExample {
    public static void main(String[] args) {
        // 多态:父类引用指向子类对象
        Person person1 = new CollegeStudent("张三", 20, "男", "计算机科学", "2023001");
        Person person2 = new Teacher("李老师", 35, "女", "计算机学院", "T1001", "教授");
        
        // 运行时多态 - 调用重写的方法
        person1.introduce(); // 调用CollegeStudent的introduce方法
        person2.introduce(); // 调用Teacher的introduce方法
        
        System.out.println();
        
        // 对象数组中的多态
        Person[] people = new Person[3];
        people[0] = new Person("普通人", 25, "男");
        people[1] = new CollegeStudent("王五", 21, "女", "数学", "2023002");
        people[2] = new Teacher("张教授", 45, "男", "物理系", "T1002", "副教授");
        
        System.out.println("多态演示:");
        for (Person person : people) {
            person.introduce(); // 运行时根据实际对象类型调用相应方法
            person.eat();       // 继承的方法
            
            // 类型检查和转换
            if (person instanceof CollegeStudent) {
                CollegeStudent student = (CollegeStudent) person;
                student.study();
            } else if (person instanceof Teacher) {
                Teacher teacher = (Teacher) person;
                teacher.teach();
            }
            System.out.println("---------");
        }
    }
}

6. 抽象类和接口

抽象类

// 抽象类
public abstract class Animal {
    protected String name;
    protected int age;
    
    public Animal(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    // 抽象方法 - 没有方法体
    public abstract void makeSound();
    
    // 具体方法
    public void sleep() {
        System.out.println(name + "正在睡觉...");
    }
    
    // 具体方法
    public void eat() {
        System.out.println(name + "正在吃东西...");
    }
    
    public String getName() {
        return name;
    }
}

接口

// 接口
public interface Swimmable {
    // 常量(默认 public static final)
    int MAX_SPEED = 10;
    
    // 抽象方法(默认 public abstract)
    void swim();
    
    // 默认方法(Java 8+)
    default void floatOnWater() {
        System.out.println("漂浮在水面上...");
    }
    
    // 静态方法(Java 8+)
    static void showMaxSpeed() {
        System.out.println("最大游泳速度:" + MAX_SPEED);
    }
}

public interface Flyable {
    void fly();
    void land();
}

实现抽象类和接口

// 具体类继承抽象类并实现接口
public class Dog extends Animal implements Swimmable {
    private String breed;
    
    public Dog(String name, int age, String breed) {
        super(name, age);
        this.breed = breed;
    }
    
    // 实现抽象方法
    @Override
    public void makeSound() {
        System.out.println(name + "汪汪叫!");
    }
    
    // 实现接口方法
    @Override
    public void swim() {
        System.out.println(name + "正在狗刨游泳...");
    }
    
    // 特有方法
    public void fetch() {
        System.out.println(name + "正在接飞盘...");
    }
    
    public String getBreed() {
        return breed;
    }
}

public class Duck extends Animal implements Swimmable, Flyable {
    public Duck(String name, int age) {
        super(name, age);
    }
    
    @Override
    public void makeSound() {
        System.out.println(name + "嘎嘎叫!");
    }
    
    @Override
    public void swim() {
        System.out.println(name + "正在水上游泳...");
    }
    
    @Override
    public void fly() {
        System.out.println(name + "正在飞翔...");
    }
    
    @Override
    public void land() {
        System.out.println(name + "正在降落...");
    }
}

7. 静态成员和final关键字

public class Car {
    // 实例变量
    private String brand;
    private String color;
    private double price;
    
    // 静态变量(类变量)
    private static int carCount = 0;
    public static final String MANUFACTURER = "汽车制造公司";
    
    // 构造方法
    public Car(String brand, String color, double price) {
        this.brand = brand;
        this.color = color;
        this.price = price;
        carCount++; // 每创建一辆车,计数器加1
    }
    
    // 实例方法
    public void displayInfo() {
        System.out.println("品牌:" + brand + ",颜色:" + color + ",价格:" + price);
    }
    
    // 静态方法
    public static int getCarCount() {
        return carCount;
    }
    
    public static void displayManufacturer() {
        System.out.println("制造商:" + MANUFACTURER);
    }
    
    // final方法 - 不能被子类重写
    public final void startEngine() {
        System.out.println("发动机启动!");
    }
    
    // Getter和Setter
    public String getBrand() {
        return brand;
    }
    
    public void setBrand(String brand) {
        this.brand = brand;
    }
    
    public String getColor() {
        return color;
    }
    
    public void setColor(String color) {
        this.color = color;
    }
    
    public double getPrice() {
        return price;
    }
    
    public void setPrice(double price) {
        this.price = price;
    }
}

// final类 - 不能被继承
public final class UtilityClass {
    // 私有构造方法 - 防止实例化
    private UtilityClass() {}
    
    public static void utilityMethod() {
        System.out.println("这是一个工具方法");
    }
}

8. 综合示例:简单的学校管理系统

import java.util.ArrayList;
import java.util.List;

// 学校类
public class School {
    private String name;
    private List<Person> members;
    
    public School(String name) {
        this.name = name;
        this.members = new ArrayList<>();
    }
    
    public void addMember(Person person) {
        members.add(person);
        System.out.println(person.getName() + " 已加入 " + name);
    }
    
    public void showAllMembers() {
        System.out.println("\n=== " + name + " 所有成员 ===");
        for (Person person : members) {
            person.introduce();
            
            if (person instanceof CollegeStudent) {
                ((CollegeStudent) person).study();
            } else if (person instanceof Teacher) {
                ((Teacher) person).teach();
            }
            System.out.println();
        }
    }
    
    public static void main(String[] args) {
        School school = new School("XX大学");
        
        // 创建学生和教师
        CollegeStudent student1 = new CollegeStudent("张三", 20, "男", "计算机科学", "2023001");
        CollegeStudent student2 = new CollegeStudent("李四", 21, "女", "数学", "2023002");
        Teacher teacher1 = new Teacher("王教授", 45, "男", "计算机学院", "T1001", "教授");
        Teacher teacher2 = new Teacher("赵老师", 35, "女", "数学系", "T1002", "讲师");
        
        // 添加成员到学校
        school.addMember(student1);
        school.addMember(student2);
        school.addMember(teacher1);
        school.addMember(teacher2);
        
        // 显示所有成员
        school.showAllMembers();
        
        // 演示多态
        System.out.println("=== 多态演示 ===");
        Person[] people = {student1, teacher1};
        for (Person person : people) {
            person.eat();
            person.introduce();
            System.out.println();
        }
    }
}

关键概念总结

  1. 类与对象:类是蓝图,对象是实例

  2. 封装:私有属性 + 公共方法

  3. 继承:extends关键字,代码复用

  4. 多态:同一接口,不同实现

  5. 抽象类:包含抽象方法的类,不能实例化

  6. 接口:完全抽象的类,支持多重实现

  7. 静态成员:属于类而不是对象

  8. final:修饰类(不可继承)、方法(不可重写)、变量(常量)

面向对象编程让代码更加模块化、可重用和易于维护,是Java编程的核心的思想,让我们一起练习吧。

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值