阶段三:高级特性
目标:掌握Java的高级特性,如异常处理、集合框架、泛型、多线程等。
1. 异常处理
try-catch
语句finally
块- 自定义异常
代码示例:
public class Main {
public static void main(String[] args) {
try {
int result = 10 / 0; // 会抛出 ArithmeticException
} catch (ArithmeticException e) {
System.out.println("捕获到异常: " + e.getMessage());
} finally {
System.out.println("无论是否异常,都会执行");
}
}
}
2. 集合框架
List
,Set
,Map
的使用
代码示例:
import java.util.ArrayList;
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
// List 示例
ArrayList<String> list = new ArrayList<>();
list.add("Java");
list.add("Python");
System.out.println("List: " + list);
// Map 示例
HashMap<String, Integer> map = new HashMap<>();
map.put("Java", 1);
map.put("Python", 2);
System.out.println("Map: " + map);
}
}
3. 泛型
- 泛型类
- 泛型方法
代码示例:
// 泛型类
class Box<T> {
private T item;
void setItem(T item) {
this.item = item;
}
T getItem() {
return item;
}
}
public class Main {
public static void main(String[] args) {
Box<String> box = new Box<>();
box.setItem("Hello");
System.out.println(box.getItem());
}
}
4. 多线程
- 创建线程的两种方式:继承
Thread
类、实现Runnable
接口
代码示例:
// 方式1:继承 Thread 类
class MyThread extends Thread {
@Override
public void run() {
System.out.println("线程运行中");
}
}
// 方式2:实现 Runnable 接口
class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println("线程运行中");
}
}
public class Main {
public static void main(String[] args) {
// 方式1
MyThread thread1 = new MyThread();
thread1.start();
// 方式2
Thread thread2 = new Thread(new MyRunnable());
thread2.start();
}
}