Java回顾案例

wen java案例 3

本文目录导读:

Java回顾案例

  1. 基础语法回顾
  2. 异常处理案例
  3. 多线程案例
  4. IO与NIO案例
  5. 网络编程案例
  6. Lambda与函数式编程案例
  7. 设计模式案例
  8. 实战练习题

我来为您整理一份Java核心知识的回顾案例,涵盖从基础到进阶的重要概念。

基础语法回顾

面向对象基础案例

/**
 * 员工管理系统 - 面向对象基础案例
 */
public class Employee {
    // 封装:私有属性
    private String name;
    private int age;
    private double salary;
    // 构造方法
    public Employee(String name, int age, double salary) {
        this.name = name;
        this.age = age;
        this.salary = salary;
    }
    // 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 < 65) {
            this.age = age;
        }
    }
    public double getSalary() {
        return salary;
    }
    public void setSalary(double salary) {
        if (salary > 0) {
            this.salary = salary;
        }
    }
    // 业务方法
    public void work() {
        System.out.println(name + "正在工作...");
    }
    @Override
    public String toString() {
        return String.format("员工{姓名='%s', 年龄=%d, 薪资=%.2f}", 
                           name, age, salary);
    }
}
// 继承案例
class Manager extends Employee {
    private double bonus;
    public Manager(String name, int age, double salary, double bonus) {
        super(name, age, salary); // 调用父类构造器
        this.bonus = bonus;
    }
    public double getBonus() {
        return bonus;
    }
    public void setBonus(double bonus) {
        this.bonus = bonus;
    }
    @Override
    public void work() {
        System.out.println(getName() + "正在管理团队...");
    }
    // 多态:父类引用指向子类对象
    public static void showEmployeeInfo(Employee emp) {
        System.out.println(emp);
        emp.work(); // 动态绑定
    }
}

集合框架使用案例

import java.util.*;
import java.util.stream.Collectors;
public class CollectionDemo {
    public static void main(String[] args) {
        // 1. List示例
        List<String> list = new ArrayList<>();
        list.add("Java");
        list.add("Python");
        list.add("JavaScript");
        // Lambda表达式遍历
        list.forEach(System.out::println);
        // 2. Map示例
        Map<String, Integer> scores = new HashMap<>();
        scores.put("张三", 85);
        scores.put("李四", 92);
        scores.put("王五", 78);
        // 遍历Map
        scores.forEach((name, score) -> 
            System.out.println(name + ": " + score));
        // 3. Stream API示例
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
        // 过滤并收集
        List<Integer> evenNumbers = numbers.stream()
            .filter(n -> n % 2 == 0)
            .collect(Collectors.toList());
        // 映射
        List<String> squared = numbers.stream()
            .map(n -> n * n)
            .map(String::valueOf)
            .collect(Collectors.toList());
        // 归约
        int sum = numbers.stream()
            .reduce(0, Integer::sum);
    }
}

异常处理案例

public class ExceptionDemo {
    // 自定义异常
    static class InsufficientBalanceException extends Exception {
        public InsufficientBalanceException(String message) {
            super(message);
        }
    }
    static class BankAccount {
        private double balance;
        public BankAccount(double balance) {
            this.balance = balance;
        }
        public void withdraw(double amount) throws InsufficientBalanceException {
            if (amount > balance) {
                throw new InsufficientBalanceException(
                    String.format("余额不足!当前余额:%.2f,需要:%.2f", 
                                 balance, amount));
            }
            balance -= amount;
            System.out.println("取款成功,剩余余额:" + balance);
        }
    }
    // 异常处理示例
    public static void main(String[] args) {
        BankAccount account = new BankAccount(1000);
        try {
            account.withdraw(1500);
        } catch (InsufficientBalanceException e) {
            System.err.println("错误:" + e.getMessage());
        } finally {
            System.out.println("操作完成");
        }
    }
}

多线程案例

import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
public class ThreadDemo {
    // 1. 继承Thread类
    static class MyThread extends Thread {
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + " 执行中");
        }
    }
    // 2. 实现Runnable接口
    static class MyRunnable implements Runnable {
        @Override
        public void run() {
            System.out.println(Thread.currentThread().getName() + " 执行中");
        }
    }
    // 3. 使用Callable和Future
    static class MyCallable implements Callable<String> {
        @Override
        public String call() throws Exception {
            Thread.sleep(1000);
            return "任务完成";
        }
    }
    // 4. 线程安全计数器
    static class SafeCounter {
        private AtomicInteger count = new AtomicInteger(0);
        public void increment() {
            count.incrementAndGet();
        }
        public int getCount() {
            return count.get();
        }
    }
    public static void main(String[] args) throws Exception {
        // 线程池示例
        ExecutorService executor = Executors.newFixedThreadPool(5);
        // 提交任务
        Future<String> future = executor.submit(new MyCallable());
        // 获取结果
        String result = future.get();
        System.out.println(result);
        // 关闭线程池
        executor.shutdown();
    }
}

IO与NIO案例

import java.io.*;
import java.nio.file.*;
import java.nio.channels.*;
public class IODemo {
    // 传统IO:文件复制
    public static void copyFileTraditional(String source, String dest) 
            throws IOException {
        try (FileInputStream fis = new FileInputStream(source);
             FileOutputStream fos = new FileOutputStream(dest);
             BufferedInputStream bis = new BufferedInputStream(fis);
             BufferedOutputStream bos = new BufferedOutputStream(fos)) {
            byte[] buffer = new byte[8192];
            int bytesRead;
            while ((bytesRead = bis.read(buffer)) != -1) {
                bos.write(buffer, 0, bytesRead);
            }
        }
    }
    // NIO:文件复制
    public static void copyFileNIO(String source, String dest) 
            throws IOException {
        Path sourcePath = Paths.get(source);
        Path destPath = Paths.get(dest);
        Files.copy(sourcePath, destPath, StandardCopyOption.REPLACE_EXISTING);
    }
    // 读取文件内容(NIO)
    public static void readFileWithNIO(String filePath) 
            throws IOException {
        Path path = Paths.get(filePath);
        // 使用Files工具类
        byte[] bytes = Files.readAllBytes(path);
        // 或使用BufferedReader
        try (BufferedReader reader = Files.newBufferedReader(path)) {
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        }
    }
}

网络编程案例

import java.net.*;
import java.io.*;
public class NetworkDemo {
    // 简单的HTTP客户端
    public static class HttpClient {
        public static String sendGet(String url) throws IOException {
            URL obj = new URL(url);
            HttpURLConnection conn = (HttpURLConnection) obj.openConnection();
            conn.setRequestMethod("GET");
            conn.setRequestProperty("User-Agent", "Mozilla/5.0");
            int responseCode = conn.getResponseCode();
            BufferedReader in = new BufferedReader(
                new InputStreamReader(conn.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();
            return response.toString();
        }
    }
    // 简单的Socket通信
    public static class ChatServer {
        public static void start() {
            try (ServerSocket serverSocket = new ServerSocket(8080)) {
                System.out.println("等待客户端连接...");
                Socket clientSocket = serverSocket.accept();
                System.out.println("客户端已连接");
                BufferedReader in = new BufferedReader(
                    new InputStreamReader(clientSocket.getInputStream()));
                PrintWriter out = new PrintWriter(
                    clientSocket.getOutputStream(), true);
                String message = in.readLine();
                System.out.println("收到消息: " + message);
                out.println("服务器已收到消息");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Lambda与函数式编程案例

import java.util.function.*;
import java.util.stream.*;
public class LambdaDemo {
    public static void main(String[] args) {
        // 1. Function接口
        Function<String, Integer> strLength = String::length;
        System.out.println(strLength.apply("Hello World")); // 11
        // 2. Predicate接口
        Predicate<String> isEmpty = String::isEmpty;
        System.out.println(isEmpty.test("")); // true
        // 3. Consumer接口
        Consumer<String> printer = System.out::println;
        printer.accept("打印消息");
        // 4. Supplier接口
        Supplier<Double> randomSupplier = Math::random;
        System.out.println(randomSupplier.get());
        // 5. 方法引用示例
        List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
        // 静态方法引用
        names.forEach(System.out::println);
        // 实例方法引用
        names.sort(String::compareToIgnoreCase);
        // 6. Optional用法
        Optional<String> optional = Optional.of("Hello");
        optional
            .filter(s -> s.length() > 3)
            .map(String::toUpperCase)
            .ifPresent(System.out::println);
    }
}

设计模式案例

// 单例模式
public class Singleton {
    private volatile static Singleton instance;
    private Singleton() {}
    public static Singleton getInstance() {
        if (instance == null) {
            synchronized (Singleton.class) {
                if (instance == null) {
                    instance = new Singleton();
                }
            }
        }
        return instance;
    }
}
// 工厂模式
interface Product {
    void create();
}
class ConcreteProductA implements Product {
    @Override
    public void create() {
        System.out.println("创建产品A");
    }
}
class ConcreteProductB implements Product {
    @Override
    public void create() {
        System.out.println("创建产品B");
    }
}
class ProductFactory {
    public static Product createProduct(String type) {
        return switch (type) {
            case "A" -> new ConcreteProductA();
            case "B" -> new ConcreteProductB();
            default -> throw new IllegalArgumentException("未知产品类型");
        };
    }
}

实战练习题

  1. 学生管理系统:使用面向对象思想实现学生信息的增删改查
  2. 文件搜索工具:递归搜索指定目录下的所有文件
  3. 多线程下载器:实现多线程分段下载文件
  4. 简易Web服务器:使用NIO实现简单的HTTP服务器

这些案例涵盖了Java开发中的核心知识点,建议您动手实践每个案例,理解其中的设计思想和编码规范。

抱歉,评论功能暂时关闭!