作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我是 Java 新手,正在尝试做一个简单的程序来帮助我进一步了解面向对象的编程。
我决定做一个电话程序。但是,在以下程序的第 5 行中,我尝试创建电话类的实例,但出现以下错误:
“没有可访问 OOPTutorial 类型的封闭实例。必须使用 OOPTutorial 类型的封闭实例限定分配(例如 x.new A()
,其中 x
是 OOPTutorial
的实例)。”
这是程序:
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/
我是一名优秀的程序员,十分优秀!