2

I used the following piece of code, which gave me an error at the point indicated:

class LinkedList{
    class pair{
            Integer petrol;
            Integer distance;

            public pair (Integer a, Integer b){
                    petrol = a;
                    distance = b;
            }
    }

    public static void main(String args[]){
            pair[] circle = {new pair(4,6), new pair(6,5), new pair(7,3), new pair(4,5)}; // error at first element of array circle!!!!!!!
    }
}

I then rectified it to this and the error dissapeared!

class LinkedList{
    static class pair{ // changed to static!!!
        Integer petrol;
        Integer distance;

        public pair (Integer a, Integer b){
            petrol = a;
            distance = b;
        }
    }

    public static void main(String args[]){
        pair[] circle = {new pair(4,6), new pair(6,5), new pair(7,3), new pair(4,5)}; //error gone!
    }
}

My question is why did the error even appear in the first place?

ERROR: No enclosing instance of type LinkedList is accessible. Must qualify the allocation with an enclosing instance of type LinkedList.

user85421
  • 28,957
  • 10
  • 64
  • 87
LoveMeow
  • 3,858
  • 9
  • 44
  • 66
  • 8
    Without the static keyword, `pair` becomes an inner class of `LinkedList`, which means each `pair` object must be associated with an instance of the enclosing `LinkedList` class. – Eran Jul 27 '17 at 09:58

1 Answers1

3

In case 1, pair is a member of LinkedList. Meaning that you can access pair through only LinkedList and not directly just like any varaible or method of that class.

A nested class is a member of its enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. Static nested classes do not have access to other members of the enclosing class.

To instantiate an inner class, you must first instantiate the outer class. Then, create the inner object within the outer object with this syntax:

OuterClass.InnerClass innerObject = outerObject.new InnerClass();

However in case 2, pair is just like any another top level class and just grouped to maintain the relation. It is not at all a member of outer class. You can access it directly.

Note: A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307