Java 提示报错:No enclosing instance of type Example is accessible. Must qualify the allocation with an E

今天在牛客网上刷题是遇到一道题(如下):

                Java 提示报错:No enclosing instance of type Example is accessible. Must qualify the allocation with an E

简单的一道关于子类继承之后调用构造函数的问题。

正确答案是:

          我是父类

          我是父类

          我是子类

在自己编写程序验证时出现下列问题:

No enclosing instance of type Example is accessible. Must qualify the allocation with an Example (e.g. x.new A() where x is an instance of Example).

意思是:类型example的封闭实例不可访问。必须使用示例限定分配(例如x.new a(),其中x是示例的实例)。

public class Example {

	 class Father {

		public Father() {

			System.out.println("我是父类");

		}

	}

	 class Child extends Father {

		public Child() {

			System.out.println("我是子类");

		}

	}

	public static void main(String[] args) {

		Father a = new Father();
		Father b = new Child();
		
	}

}

分析原因:内部类是动态的(无static关键字修饰),而main方法是静态的,普通的内部类对象隐含地保存了一个引用,指向创建它的外围类对象,所以要在static方法(类加载时已经初始化)调用内部类的必须先创建外部类。即应该这样建“DanymicTest test = new StaticCallDynamic().new DanymicTest();”其中StaticCallDynamic为外部类,DanymicTest为内部动态类;如果将内部内修改为静态类,可以在main中直接创建内部类实例。

内部类用static修饰之后错误消失。结果:

Java 提示报错:No enclosing instance of type Example is accessible. Must qualify the allocation with an E

 

上一篇:SDN Mininet安装脚本(shell版,全自动,解放双手)仅适用于Ubuntu


下一篇:2linux输入子系统-按键驱动程序