gpt4 book ai didi

java - Java中如何解决这个 "non-static variable"问题?

转载 作者:行者123 更新时间:2023-12-02 13:00:31 26 4
gpt4 key购买 nike

public class InterfaceTest {
interface InterfaceA {
int len = 1 ;
void output();
}

interface InterfaceB {
int len = 2 ;
void output();
}

interface InterfaceSub extends InterfaceA, InterfaceB { }

public class Xyz implements InterfaceSub {

public void output() {
System.out.println( "output in class Xyz." );
}

public void outputLen(int type) {
switch (type) {
case InterfaceA.len:
System.out.println( "len of InterfaceA=." +type);
break ;
case InterfaceB.len:
System.out.println( "len of InterfaceB=." +type);
break ;
}
}
}

public static void main(String[] args) {
Xyz xyz = new Xyz();
xyz.output();
xyz.outputLen(1);
}
}

嗨,我想学习Java的接口(interface)和多重继承概念。我找到上面的代码并尝试编译它,但出现以下错误。我不知道如何使代码工作,谁可以帮忙?谢谢!

test$ javac InterfaceTest.java 
InterfaceTest.java:33: error: non-static variable this cannot be referenced from a static context
Xyz xyz = new Xyz();
^
1 error

最佳答案

这是因为非静态内部类无法在静态方法中实例化,因为它没有可供使用的封闭类的实例。

如果将 Xyz 定义为静态内部类,它应该可以工作:

public static class Xyz implements InterfaceSub {
....
}

或者,您可以在封闭类的实例中创建 Xyz - 此处不需要,但如果 Xyz 需要访问封闭类的某些成员变量,则需要这样做。

关于java - Java中如何解决这个 "non-static variable"问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11733255/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com