gpt4 book ai didi

java - 为什么只有当我有内部类时才会出现 "non-static variable this cannot be referenced from a static context"错误?

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:48:14 26 4
gpt4 key购买 nike

我在静态与非静态的概念上挣扎。我正在研究这个 Thread 示例程序(修改自 here originally ),当我使用内部类时,我会得到错误:

Error: non-static variable this cannot be referenced from a static context

这是导致错误的代码:

public class Main2 {
public static void main(String[] args) {
Thread simple = new Thread(new SimpleTask());
simple.start();
}


class SimpleTask implements Runnable {
public void run() {

}

;
}

class DaemonTask implements Runnable {
public void run() {
int i = 0;
}
}

}

但是,当我把它分解成 3 个类时,没有错误……也就是说,如果我做到了:

public class Main2 {  
/* contents */
}

class SimpleTask implements Runnable {
/* contents */
}

class DaemonTask implements Runnable {
/* contents */
}

然后编译就好了。为什么我们将它分成另一个类很重要?

最佳答案

你需要一个外部类实例(Main2)来访问内部类实例(SimpleTask)。

试试这个:

    Thread simple = new Thread(new Main2().new SimpleTask());

Oracle trails 上检查内部类

关于java - 为什么只有当我有内部类时才会出现 "non-static variable this cannot be referenced from a static context"错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15575918/

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