Java OOP – Basics of Object-Oriented Programming

inner-classesjavaoopstatic

I have a problem that keeps stalling me from advancing further, this error is not logical at all in my opinion , I am learning from a book and the code is from there.
This is the code :

package test_area;

public class clzzz {

    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 circle1 = new SimpleCircle();

    }



}

This is the error
enter image description here

If I eliminate the static from void main the error vanishes, but doing that I am altering the signature of the main method….. I am really confuse, followed the code from the book word by word.

Why in the name of God do I need the static tag ? I don't need to oblige the respective class to have only one instance since I can control it's instances by the names of the objects thus static is just a barrier ?

Best Answer

You defined SimpleCircle as an inner class, that is an unnecessary complication here and it is what is keeping this from compiling. Move the SimpleCircle class declaration out from inside the declaration of clzzz and you'll fix the problem.

Alternatively you could make SimpleCircle a static inner class by adding the static keyword. If you keep this as a static inner class then, if you can use it outside of clzzz, you'll need to refer to it using the outer class as well as the inner class (clzzz.SimpleCircle) so that the JVM can find it.

Typically static inner classes are used for organizational purposes, because you have something you use along with another class but it doesn't depend on it (see java.util.Map.Entry for an example, although it's an interface and not a class).

static doesn't mean you can have only one instance. In the context of a class definition it means that there is no dependency on an instance of the outer class. You still can create multiple instances using the static inner class (again, think of Map and Map.Entry, where you can iterate through all the entries of the map, each one is a separate instance of Map.Entry). You can think of static as meaning, "you don't need an object instantiated from the class where this thing is defined."

Making something a non-static inner class means objects of the inner class are accessing things in the scope of the outer class' instance, so you can't create an instance of the inner class without a reference an instance of the outer class, and that's what the compiler is complaining about.

Related Question