【问题标题】:ERROR: No enclosing instance of type OOPTutorial is accessible错误:无法访问 OOPTutorial 类型的封闭实例
【发布时间】:2023-03-24 17:18:01
【问题描述】:

我是 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


【解决方案1】:

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

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

  1. 只能在未标记为 static 的 OOPTutorial-method 中执行 new phone(),或

  2. 您需要将phone 设为顶级类(即将其移出OOPTutorial 的范围),或者

  3. 您需要将内部类phone 设为静态(通过将static 放在类声明前面)

【讨论】:

  • 鉴于他是初学者,您想补充一点解释吗? (即一个内部类有一个对封闭类的隐式引用——但没有,因为它是从静态方法调用的)。
  • 谢谢大家,现在我明白了,程序运行了:D
猜你喜欢
  • 2015-12-16
  • 2011-12-15
  • 2016-11-20
  • 2013-04-11
  • 2012-06-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多