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!

2
  • 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? Commented Jul 18, 2012 at 14:39
  • Possible duplicate of Java - No enclosing instance of type Foo is accessible Commented Mar 4, 2016 at 0:36

3 Answers 3

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:

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.