No enclosing instance of type Hello is accessible

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.