【问题标题】:No enclosing instance is accessible. Must qualify the allocation with an enclosing instance of type (e.g. x.new A() where x is an instance of ) [duplicate]没有可访问的封闭实例。必须使用类型的封闭实例来限定分配(例如 x.new A() 其中 x 是 的实例)[重复]
【发布时间】:2018-05-12 11:50:49
【问题描述】:

我是编程新手,明年我将在大学学习它。在我的 public static void main ...我不能创建一个新的 SimpleCircle。这个错误只发生在我的圈子里。非常感谢你的帮助! :)

public class TestSimpleCircle {

    class SimpleCircle {
        double radius;

        SimpleCircle(){
            radius = 1;
        }

        SimpleCircle(double newRadius){
            radius = newRadius;
        }

        double getArea() {
            return radius * radius * Math.PI;
        }

        double getPerimeter() {
            return 2 * radius * Math.PI;
        }

        void setRadius(double newRadius) {
            radius = newRadius;
        }
    }

    public static void main(String [] args) {
        SimpleCircle circle = new SimpleCircle();
        System.out.println("the area of the circle of radius "+circle.radius+" is "+circle.getArea());

        SimpleCircle circle2 = new SimpleCircle(25);
        System.out.println("the area of the circle of radius "+circle2.radius+" is "+circle2.getArea());

        SimpleCircle circle3 = new SimpleCircle(125);
        System.out.println("the area of the circle of radius "+circle3.radius+" is "+circle3.getArea());

        circle.radius = 100;
        System.out.println("The area of the circle of radius "+circle.radius+" is "+circle.getArea());
    }
}

【问题讨论】:

  • 将内部类设为静态。

标签: java class


【解决方案1】:

SimpleCircle 是类TestSimpleCircle 的内部类。这意味着您首先需要一个封闭类对象的实例,例如:

TestSimpleCircle tsc = new TestSimpleCircle();

现在您可以创建与封闭TestSimpleCircle 类的实例连接的内部类实例:

SimpleCircle sc = tsc.new SimpleCircle();

如您所见,要创建内部类对象的实例,您必须指定您希望它属于哪个封闭类对象(在您的示例中使用 tsc.new)。

如果你需要创建一个没有封闭类对象实例的 SimpleCircle 实例,你应该将这个类声明为static class SimpleCircle{code of your class here}

【讨论】:

    【解决方案2】:

    您将 SimpleCircle 类声明为 TestSimpleCircle 的内部类。 您需要将其移动到单独的文件中或将其声明为

    static class SimpleCircle
    

    【讨论】:

    • 我的问题是没有在 tomcat 中重新加载应用程序!它需要使用更新的内部类作为静态重新加载类文件。仅仅替换服务器文件是不够的 - 必须重新加载应用程序:)
    • @Skychan,您的评论与答案或问题有什么关系?错误的窗口?
    • 好点,我的评论可能会更好地解决这个问题,或者作为它自己的“解决方案”。我不介意移动它,我想我只是认为我的情况与 OP 不同,但有完全相同的错误,所以我想帮助其他与我出于相同原因来到这里的人,他们可能会看到我的愚蠢问题/答案,因为每个人都首先查看接受的答案。如果你建议,我会移动它。
    猜你喜欢
    • 1970-01-01
    • 2012-03-24
    • 1970-01-01
    • 2013-09-12
    • 2012-09-10
    • 1970-01-01
    • 1970-01-01
    • 2011-12-15
    相关资源
    最近更新 更多