Re: I don't quite understand a "static context" error message
Dan wrote On 08/22/07 16:34,:
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?
As it stands, Parent is an inner class belonging
to an InstanceofDemo object -- you cannot create a
Parent in isolation, but only in connection with the
InstanceofDemo object that owns it. In the static
method main(), there is no InstanceofDemo object in
sight, so the compiler complains.
When you move Parent outside InstanceofDemo, it
becomes a free-standing class that has no connection
to InstanceofDemo, and does not need to be associated
with an InstanceofDemo object.
--
Eric.Sosman@sun.com