J03 Java基础 04:补充

Java修饰符


访问控制修饰符

访问控制修饰符用于控制类、方法、变量等的访问权限。

修饰符 同类 同包 子类 其他包
private
无修饰符
protected
public

类级别修饰符

  • final

    表示类不能被继承:

    1
    2
    final class Example {}

  • abstract

    表示类是抽象类,不能实例化,必须由子类实现:

    1
    2
    3
    4
    abstract class Example {
    abstract void display();
    }

  • strictfp

    用于限制浮点运算精度,确保结果一致(跨平台):

    1
    2
    strictfp class Example {}


方法级别修饰符

  • final

    方法不能被重写:

    1
    2
    3
    4
    class Example {
    final void display() {}
    }

  • abstract

    方法没有实现,必须由子类实现:

    1
    2
    3
    4
    abstract class Example {
    abstract void display();
    }

  • static

    静态方法,属于类本身,可直接通过类名调用:

    1
    2
    3
    4
    class Example {
    static void display() {}
    }

  • synchronized

    同步方法,确保线程安全:

    1
    2
    3
    4
    class Example {
    synchronized void display() {}
    }

  • native

    声明本地方法,用于调用非 Java 代码(如 C/C++):

    1
    2
    3
    4
    class Example {
    native void display();
    }

  • strictfp

    确保方法中的浮点运算遵循 IEEE 754 标准:

    1
    2
    strictfp void display() {}


变量级别修饰符

  • final

    表示变量不可修改:

    1
    2
    final int MAX_VALUE = 100;

  • static

    静态变量,属于类本身,所有实例共享:

    1
    2
    static int count;

  • transient

    表示变量不会被序列化:

    1
    2
    3
    4
    class Example {
    transient int tempData;
    }

  • volatile

    表示变量在多线程中可见,强制从主存读取:

    1
    2
    volatile int counter;

Java泛型


La généricité, 或者generics是Java 提供的一种允许类、接口和方法能够处理不同类型的对象,同时保持类型安全性的机制。与c++的模板很像。

使用泛型的类和方法额外使用<> 运算符接受具体类型,例如之前描述过的List<Integer> a = new ArrayList<Integer>(); 。值得注意的是,后一个Integer 不是必要的。


泛型类

下例为一个使用泛型类的例子。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
class Box<T> {
private T item;

public void setItem(T item) {
this.item = item;
}

public T getItem() {
return item;
}
}

public class Main {
public static void main(String[] args) {
Box<String> stringBox = new Box<>();
stringBox.setItem("Hello");
System.out.println(stringBox.getItem());

Box<Integer> intBox = new Box<>();
intBox.setItem(123);
System.out.println(intBox.getItem());
}
}


泛型方法

下例为一个使用泛型方法的例子。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class Utility {
public static <T> void printArray(T[] array) {
for (T element : array) {
System.out.println(element);
}
}
}
public class Main {
public static void main(String[] args) {
Integer[] intArray = {1, 2, 3};
String[] strArray = {"A", "B", "C"};

Utility.printArray(intArray);
Utility.printArray(strArray);
}
}


泛型接口

下例为一个使用泛型接口的例子。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
interface Pair<K, V> {
K getKey();
V getValue();
}
class KeyValue<K, V> implements Pair<K, V> {
private K key;
private V value;

public KeyValue(K key, V value) {
this.key = key;
this.value = value;
}

public K getKey() {
return key;
}

public V getValue() {
return value;
}
}

public class Main {
public static void main(String[] args) {
KeyValue<String, Integer> kv = new KeyValue<>("Age", 30);
System.out.println(kv.getKey() + ": " + kv.getValue());
}
}


除了使用<T> 的泛型,还有其他通配符形式,如:

  • 无界通配符 <?> :表示可以接受任何类型,但只能读取数据,不能写入。

    1
    2
    3
    4
    5
    public void printList(List<?> list) {
    for (Object item : list) {
    System.out.println(item);
    }
    }

  • 上界通配符 <? extends Type> :表示可以接受 Type 类型及其子类型。

    1
    2
    3
    4
    5
    public void processNumbers(List<? extends Number> numbers) {
    for (Number num : numbers) {
    System.out.println(num.doubleValue());
    }
    }

  • 下界通配符 <? super Type> ,表示可以接受 Type 类型及其父类型。

    1
    2
    3
    4
    public void addNumbers(List<? super Integer> list) {
    list.add(10);
    list.add(20);
    }

Java异常


Java所有的异常都是Object->Throwable 的子类。具体来说,异常有两大分支:

  • Error用于描述系统错误,通常无法恢复。
    • OutOfMemoryError,通常不处理。
  • Exception可恢复的异常,分为两类:
    • RuntimeException(运行时异常)
      • NullPointerExceptionArithmeticException
      • 不强制要求处理,可以选择捕获。
    • CheckedException(受检异常,需要显式处理)
      • 必须在编译时处理,例如 IOExceptionSQLException
      • 方法中必须显式声明 throws 或通过 try-catch 处理。

try-catch

1
2
3
4
5
try {
int result = 10 / 0; // 会抛出 ArithmeticException
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero: " + e.getMessage());
}

也可以同时捕获多种异常:

1
2
3
4
5
6
7
try {
// 可能抛出多个异常
} catch (IOException e) {
// 处理 IOException
} catch (ArithmeticException e) {
// 处理 ArithmeticException
}

finally finally 块用于清理资源,无论是否发生异常都会执行。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
FileInputStream file = null;
try {
file = new FileInputStream("test.txt");
// 文件操作
} catch (IOException e) {
System.out.println("File not found");
} finally {
if (file != null) {
try {
file.close();
} catch (IOException e) {
System.out.println("Error closing file");
}
}
}


throw throws

1
2
3
4
5
public void validateAge(int age) {
if (age < 18) {
throw new IllegalArgumentException("Age must be at least 18");
}
}

自定义异常

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}

public class Main {
public static void main(String[] args) {
try {
throw new CustomException("This is a custom exception");
} catch (CustomException e) {
System.out.println(e.getMessage());
}
}
}

Java注解


Java 中的注解(Annotation)是一种特殊的元数据,以为类、方法、变量等提供额外的信息。

Java 提供了一些内置的标准注解:

  1. @Override

    • 表示当前方法重写了父类的方法。
    • 如果父类没有对应的方法,编译器会报错。

    1
    2
    3
    4
    @Override
    public String toString() {
    return "This is an overridden method";
    }

  2. @Deprecated

    • 标记一个元素(类、方法、字段等)已过时,不建议使用。

    • 使用该元素时,编译器会发出警告。

      1
      2
      3
      4
      5
      @Deprecated
      public void oldMethod() {
      System.out.println("This method is deprecated");
      }

  3. @SuppressWarnings

    • 用于抑制编译器警告。
    • 常见的值:
      • "unchecked":忽略未检查的操作(如使用泛型时的类型检查)。
      • "serial":忽略未声明 serialVersionUID 的警告。

    1
    2
    3
    4
    5
    6
    @SuppressWarnings("unchecked")
    public void useRawType() {
    List list = new ArrayList(); // 未使用泛型
    list.add("String");
    }

Comparator接口


Comparator<T> 是 Java 中的一个接口,位于 java.util 包中,用于定义自定义排序逻辑。

Comparator 接口有以下两个重要方法:

  1. int compare(T o1, T o2)

    • 比较两个对象 o1o2
    • 返回值含义:
      • 负数:如果 o1 小于 o2
      • 0:如果 o1 等于 o2
      • 正数:如果 o1 大于 o2

    1
    2
    3
    4
    5
    6
    7
    8

    public class NameComparator implements Comparator<String> {
    @Override
    public int compare(String s1, String s2) {
    return s1.compareTo(s2);
    }
    }

  2. boolean equals(Object obj)(可选):

    • 用于判断两个比较器是否相等。
    • 两个函数对于相等的判断必须一致