Re: I don't quite understand a "static context" error message
Dan (junk63043@yahoo.com) wrote:
: Here's a slightly altered bit of code from Sun's tutorial:
: package instanceofdemo;
: public class InstanceofDemo {
: public InstanceofDemo() {
: }
: public static void main(String[] args) {
: Parent obj1 = new Parent();
: System.out.println("obj1 instanceof Parent: " + (obj1
: instanceof Parent));
: }
: class Parent{
: }
: } //"Class End Brace"
: The "Parent obj1 = new Parent();" line gets this error:
: non-static variable this cannot be referenced from a static context
: If I move the "Class End Brace" above the "class Parent{" line, the
: error goes away.
: I'm just on the edge of understanding why that should be. Can anyone
: get me the rest of the way there? What's the compiler seeing that
: causes this?
Well first, as an aside, I prefer to align my braces vertically, because
then you can more easily see how the nesting works.
In your example, the Parent class is _inside_ the InstanceofDemo class.
Defining a class inside another class is perfectly legit, and is
conceptually the same as defining anything else inside a class, such as
member variables and methods.
Basically, each instance of "InstanceofDemo" has its own version of a
class called "Parent".
This would be much clearer if you had a number of different classes, each
of which defined their own version of a class called "Parent".
And just like when you access a member variable and need to provide the
object that contains that instance of the variable, so here, to access the
"Parent" class, you need to indicate _which_ "Parent" class by providing
the object that contains that instance of the class definition (so to
speak).
When you move the brace then the Parent definition is now outside the
"InstanceofDemo" class. The code still compiles because either syntax is
legal.