gpt4 book ai didi

java - 错误 : No enclosing instance of type OOPTutorial is accessible

转载 作者:行者123 更新时间:2023-12-04 05:43:00 24 4
gpt4 key购买 nike

我是 Java 新手,正在尝试做一个简单的程序来帮助我进一步了解面向对象的编程。

我决定做一个电话程序。但是,在以下程序的第 5 行中,我尝试创建电话类的实例,但出现以下错误:

“没有可访问 OOPTutorial 类型的封闭实例。必须使用 OOPTutorial 类型的封闭实例限定分配(例如 x.new A(),其中 xOOPTutorial 的实例)。”

这是程序:

public class OOPTutorial {

public static void main (String[] args){

phone myMobile = new phone(); // <-- here's the error
myMobile.powerOn();
myMobile.inputNumber(353851234);
myMobile.dial();

}

public class phone{
boolean poweredOn = false;
int currentDialingNumber;

void powerOn(){
poweredOn = true;
System.out.println("Hello");
}
void powerOff(){
poweredOn = false;
System.out.println("Goodbye");
}
void inputNumber(int num){
currentDialingNumber = num;
}
void dial(){
System.out.print("Dialing: " + currentDialingNumber);
}
}
}

最佳答案

如果您不熟悉 Java,这可能对您没有意义,但是实例化非静态内部类 ( phone ) 需要封闭类 ( OOPTutorial ) 的实例。

用简单的英语来说,这大致意味着你要么

  • 只能做new phone()在未标记为 static 的 OOPTutorial 方法中, 或
  • 您需要制作 phone顶级类(即将其移出 OOPTutorial 的范围),或
  • 你需要制作内部类phone作为静态(通过将 static 放在类声明前面)
  • 关于java - 错误 : No enclosing instance of type OOPTutorial is accessible,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11031272/

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