1.static keywords
- The decorated members are shared by all objects (including member variables and methods).
- A decorated member takes precedence over the existence of an object.
- stored in the static area of the method area (shared data area).
- Static methods can only access static members.
- The this or Super keyword cannot be used in a static method.
- The main function is static and can only call the static method.
- Static code blocks run as the class is loaded (once only). Used to initialize a class.
Q:
I have the following code:
1:class Hello {
2: class Thing {
3: Public int size;
4:
5: Thing () {
6: size = 0;
7: }
8: }
9:
Ten: Public Static void Main (string[] args) {
One : New Thing ();
: System.out.println ("Hello, world!");
: }
: }
It refuses to compile. I get at the No enclosing instance of type Hello is accessible."
creates a new Thing.
A:
You ' ve declared the class Thing as a non-static inner class. That means it must is associated with an instance of the Hello class.
In the Your code, you ' re trying to create a instance of Thing from a static context. That's what the compiler are complaining about.
There is a few possible solutions. Which solution to use depends on what do you want to achieve.
Change Thing to be a static nested class.
1:staticclass Thing
-
Create an instance of the Hello, then create an instance of Thing.
1:publicstaticvoid main (string[] args)
2: {
3: New Hello ();
4: Thing thing1 = h.new//Hope this syntax are right, typing on the fly:P
5: }
Move Thing out of the Hello class.
No enclosing instance of type Hello is accessible