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

编程入门 行业动态 更新时间:2024-10-09 12:28:03

Java 提示<a href=https://www.elefans.com/category/jswz/34/1771188.html style=报错: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

本文发布于:2024-02-07 06:23:40,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1753861.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:报错   提示   enclosing   Java   instance

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!