2

I thought this was pretty simple, because I am pretty sure I have done it before, but I cant seem to get this to work. My class is:

public class City
{
    String start = null;
    String end = null;
    int weight = 0;
}

and I am doing:

City cityGraph[] = new City[l];

When I try to access cityGraph[x].start for example, I get a null pointer exception, so I figured I need to initialize every element in the array as well, so I do:

for(int j = 0; j < l; j++)
        {
            cityGraph[j] = new City();
        }

but it is giving me this error:

No enclosing instance of type Graphs is accessible. 
Must qualify the allocation with an enclosing instance 
of type Graphs (e.g. x.new A() where x is an instance of Graphs).

I have no idea what this means, or how to fix it. Any help would be appreciated!

Wingdom
  • 439
  • 2
  • 10
  • 23
  • It seems to think you are trying to use type Graphs. Could you post the entire code as is and see if there's a typo? – nolegs Jul 18 '12 at 14:39
  • Possible duplicate of [Java - No enclosing instance of type Foo is accessible](http://stackoverflow.com/questions/9560600/java-no-enclosing-instance-of-type-foo-is-accessible) – fabian Mar 04 '16 at 00:36

3 Answers3

5

That can happen when you have declared public class City as an inner class of public class Graphs like so

public class Graphs {

    public class City {
    
    }

}

This way the City cannot be constructed without constructing a Graphs instance first.

You'd need to construct the City as follows:

cityGraph[j] = new Graphs().new City();
// or
cityGraph[j] = existingGraphsInstance.new City();

This makes honestly no sense. Rather either extract the City into a standalone class,

public class Graphs {

}
public class City {

}

or make it a static nested class by declaring it static.

public class Graphs {

    public static class City {
    
    }

}

Either way, you'll be able to construct a new City by just new City().

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
1

It seems that your class is not a static inner class, which means that it requires an instance of the outer class in order to be instantiated.

More on Static vs Inner classes http://mindprod.com/jgloss/innerclasses.html

MrHappyAsthma
  • 6,332
  • 9
  • 48
  • 78
0

I actually have the answer to my own question. Making the class static fixed it. I don't know why I didn't think of this until after I posted... Hopefully this will help someone in the future.

Wingdom
  • 439
  • 2
  • 10
  • 23