This question already has answers here:
Java - No enclosing instance of type Foo is accessible

(6个答案)


3年前关闭。




我是编程的新手,明年我将在uni学习。在我的公共(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());
    }
}

最佳答案

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

static class SimpleCircle

10-05 22:54