Java报错--xxx is not an enclosing class

发布时间 2023-07-09 16:23:43作者: 虫萤映雪

Java报错--xxx is not an enclosing class

一、出错原因

​ 此类问题一般出现在定义了外部类和内部类之外,声明内部类对象时代码书写不规范导致的语法错误。

二、代码示例

1.声明外部类和内部类,代码如下:

public class Demo01 {
    private String name = "张三";
    private int age = 25;

    public class Inner {
        private String name1 = "李四";
        private int age1 = 26;
//        public static print(){}//内部类不能声明静态成员
        public void show(){//内部类可以直接调用外部类的私有成员而不破坏封装
            System.out.println("姓名:" + name + "--年龄:" + age);//外部类属性
            System.out.println("姓名1:" + name1 + "--年龄1:" + age1);//内部类属性
        }
    }
}

2.书写测试类,定义内部类对象,代码如下:

public class Application {
    public static void main(String[] args){
        Demo01 outer = new Demo01();//定义外部类对象
        Inner inner2 = new Demo01.new Inner();//定义内部类对象,此时报错
        inner2.show();
    }
}

三、解决方法

​ 一般来说,定义内部类对象主要有两种形式,代码如下:

public class Application {
    public static void main(String[] args){
        Demo01 outer = new Demo01();//定义外部类对象
        Inner inner1 = outer.new Inner();//定义内部类对象,第一种方式
        inner1.show();
        Inner inner2 = new Demo01().new Inner();//定义内部类对象,第二种方式
        inner2.show();
    }
}

之所以会出现“xxx is not an enclosing class”报错,是因为在使用定义内部类对象的第二种方式的时候,书写出错,因此,应当将

Inner inner2 = new Demo01.new Inner();//定义内部类对象,此时报错

改为

Inner inner2 = new Demo01().new Inner();//定义内部类对象,第二种方式

程序即可正常运行。

四、总结

行文中如有错漏,欢迎大家随时指正,感谢!