Possible Duplicate:
non-static variable cannot be referenced from a static context (java)
public class DemoJava {
public class Hello {
void fun()
{
System.out.println("This is static fun man!!");
}
}
public static void main(String[] args) {
Hello hello = new Hello();
hello.fun();
}
}
In this example it will give me an error since I am trying to access a non-static class from a static method. Fine. For instance, if I have the same Hello
class in another file and I do the same thing it does not give me an error.
Even in that case we are trying to access non-static class from static method. But that doesn't give any error. Why?
You can always call the static functions of a class without having an instance
Hello.fun();
should work!
No, it will give you an error because you're trying to create an instance of an inner class (which implicitly has a reference to an instance of the enclosing class) when you don't have an instance of the enclosing class.
The problem isn't the call to
fun()
- it's the constructor call.For example, you can fix this by using:
Or you could just make it a nested but not inner class, by changing the class declaration to:
Read section 8.1.3 of the JLS for more information on inner classes, and section 15.9.2 for determining enclosing instances for a class instance creation expression:
Make class
Hello
staticYour inner class
Hello
dous not need access to an instance of the outer classDemoJava
therefore it can be made static.yes, it will give you error, correct way of doing it is
you have to create an instance of
Outer class
in-order to create the instance of yourinner class
.From Documentation:
syntax: