明白!这里给你几个Java SE核心知识点的经典代码示例,涵盖面向对象、异常处理、集合、多线程和Lambda表达式,帮助你快速理解和巩固。


1. 面向对象 — 类和继承示例

// 父类
class Animal {
    String name;
    Animal(String name) { this.name = name; }
    void speak() {
        System.out.println(name + " 叫声");
    }
}

// 子类继承父类,重写方法
class Dog extends Animal {
    Dog(String name) { super(name); }
    @Override
    void speak() {
        System.out.println(name + " 汪汪叫");
    }
}

public class OOPDemo {
    public static void main(String[] args) {
        Animal a = new Animal("动物");
        Dog d = new Dog("旺财");
        a.speak();
        d.speak();
    }
}

2. 异常处理示例

public class ExceptionDemo {
    public static void main(String[] args) {
        try {
            int result = divide(10, 0);
            System.out.println("结果: " + result);
        } catch (ArithmeticException e) {
            System.out.println("捕获异常: 除数不能为零");
        } finally {
            System.out.println("无论是否异常都会执行");
        }
    }

    static int divide(int a, int b) throws ArithmeticException {
        return a / b;
    }
}

3. 集合框架示例 — ArrayList 使用

import java.util.ArrayList;

public class CollectionDemo {
    public static void main(String[] args) {
        ArrayList<String> list = new ArrayList<>();
        list.add("苹果");
        list.add("香蕉");
        list.add("橘子");

        for (String fruit : list) {
            System.out.println(fruit);
        }
    }
}

4. 多线程示例 — 继承 Thread 类

class MyThread extends Thread {
    public void run() {
        for (int i = 0; i < 5; i++) {
            System.out.println("线程 " + Thread.currentThread().getName() + " 输出: " + i);
            try {
                Thread.sleep(100); // 休眠100毫秒
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

public class ThreadDemo {
    public static void main(String[] args) {
        MyThread t1 = new MyThread();
        MyThread t2 = new MyThread();
        t1.start();
        t2.start();
    }
}

5. Java 8 Lambda 和 Stream 简单示例

import java.util.Arrays;
import java.util.List;

public class LambdaDemo {
    public static void main(String[] args) {
        List<String> list = Arrays.asList("苹果", "香蕉", "橘子", "芒果");
        
        // 使用 Lambda 遍历打印
        list.forEach(fruit -> System.out.println(fruit));

        // 使用 Stream 过滤并打印长度大于2的水果名
        list.stream()
            .filter(f -> f.length() > 2)
            .forEach(System.out::println);
    }
}