Interface
接口是对行为的抽象。
- abstract method, Java 8以前接口只能有抽象方法
- default method,提供方法体,Java 8 以后有
- static method, 提供方法体,Java 8 以后有,可以通过Interface.method()调用
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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
| public interface MyInterface {
// 抽象方法
void abstractMethod();
// 默认方法
default void defaultMethod() {
System.out.println("这是接口的默认方法");
privateHelperMethod(); // 调用私有辅助方法(注意:私有方法是Java 9的特性,这里仅为示例)
}
// 静态方法
static void staticMethod() {
System.out.println("这是接口的静态方法");
}
// 私有辅助方法(Java 9 特性,但为了完整性展示,包含在此)
private void privateHelperMethod() {
System.out.println("这是接口的私有辅助方法");
}
}
public class MyClass implements MyInterface {
@Override
public void abstractMethod() {
System.out.println("实现接口的抽象方法");
}
// 可以选择覆盖默认方法
@Override
public void defaultMethod() {
System.out.println("覆盖接口的默认方法");
MyInterface.super.defaultMethod(); // 调用接口的默认方法
}
}
public class Main {
public static void main(String[] args) {
MyClass myClass = new MyClass();
// 调用实现的抽象方法
myClass.abstractMethod();
// 调用默认方法
myClass.defaultMethod(); // 注意这里调用的是覆盖后的版本
// 调用接口的静态方法
MyInterface.staticMethod();
}
}
|
Abstract Class
抽象类通常作为基类,比如 Person,Animal。因为不同子类的某种方法的 body可能不一样,所以把这些方法作为abstract method放在抽象类中。
抽象类可以继承另一个类,也可以实现多个interface。
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
30
31
32
| public interface Sing {
public void sing();
}
public interface Dance {
public void dance();
}
public abstract class Animal implements Dance, Sing{
@Override
public void dance(){
System.out.println("Animal dance");
}
@Override
public void sing(){
System.out.println("Animal sing");
}
abstract void eat();
}
public class Cat extends Animal{
@Override
public void eat() {
System.out.println("cat eat");
}
}
public class Dog extends Animal{
@Override
public void eat() {
System.out.println("Dog eats");
}
}
|
- Sing和Dance都代表能力,所以作为Interface,被Animal这个抽象类实现。
- Animal类提供abstract method eat()
- 之后Cat和Dog类又为eat()方法提供了不同的方法体。
自动装箱&自动拆箱
- 自动装箱:
将 基本类型 自动转换为对应的 包装类对象,实际调用 Integer.valueOf()、Double.valueOf() 等方法。
1
2
| int num = 10;
Integer boxedNum = num; // 自动装箱(int → Integer)
|
自动拆箱:将 包装类对象 自动转换为 基本类型。实际调用 intValue()、doubleValue() 等方法。
性能问题:自动装箱/拆箱会创建临时对象,在循环中频繁使用可能导致性能下降。
包装类对象比较时,== 比较的是 内存地址,不是数值!
1
2
3
4
5
6
7
| Integer a = 127;
Integer b = 127;
System.out.println(a == b); // true(JVM 缓存了小整数对象)
Integer c = 128;
Integer d = 128;
System.out.println(c == d); // false(超出缓存范围,新建对象)
|