首页 Java Interface成员变量问题
文章
取消

Java Interface成员变量问题

实现多个接口,同名变量问题

1
2
3
4
5
6
7
8
9
10
11
12
13
public class HelloWorld implements A,B{
    public static void main(String []args) {
        HelloWorld hello = new HelloWorld();
        System.out.println(hello.ha);
    }
}
interface A{
    int ha=0;
}

interface B{
    int ha=1;
}

这段代码 编译时会报错

1
2
java: 对ha的引用不明确
  test.A 中的变量 ha 和 test.B 中的变量 ha 都匹配

实现接口时,成员变量问题

1
2
3
4
5
6
7
8
9
public class HelloWorld implements A{
    public static void main(String []args) {
        HelloWorld hello = new HelloWorld();
        System.out.println(hello.ha);
    }
}
interface A{
    int ha=0;
}

这段代码不会出错,不是说接口只能有静态变量吗,为什么这里有个成员变量?

利用反汇编工具javap,查看字节码文件

image-20230306110833300

发现ha变量前自动加上了public static final 来进行修饰,原来接口里所有的变量必须用public static final修饰,所以可以省略不写

本文由作者按照 CC BY 4.0 进行授权

Git push时出现username for https github.com

-