Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]

Tags:

java

class

I'm new to programming and I'll be studying it next year in uni. In my public static void main ... I can't create a new SimpleCircle. This error occurs only on my circle. Thank you very much for the help! :)

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());
    }
}
like image 841
Nick Ninov Avatar asked Nov 28 '17 21:11

Nick Ninov


2 Answers

You declared you SimpleCircle class as inner class for TestSimpleCircle. You need either move it into a separate file or declare it as

static class SimpleCircle
like image 127
Ivan Avatar answered Oct 14 '22 05:10

Ivan


SimpleCircle is an inner class of class TestSimpleCircle. This means that you first need an instance of object of enclosing class, for example:

TestSimpleCircle tsc = new TestSimpleCircle();

Now you are able to create an instance of inner class that is connected with an instance of enclosing TestSimpleCircle class:

SimpleCircle sc = tsc.new SimpleCircle();

As you see, to create an instance of object of inner class you had to specify to which exactly object of enclosing class you want it to belong (with the tsc.new in your example).

If you need to create an instance of SimpleCircle without instance of object of enclosing class you should have declared this class as static class SimpleCircle{code of your class here}

like image 35
Przemysław Moskal Avatar answered Oct 14 '22 05:10

Przemysław Moskal