zoukankan      html  css  js  c++  java
  • No enclosing instance of type Hello is accessible

    1.static 关键字

    • 修饰的成员被所有对象共享(包括成员变量和方法)。
    • 修饰的成员优先于对象存在。
    • 存储于方法区(共享数据区)的静态区中。
    • 静态方法只能访问静态成员。
    • 静态方法中不可以使用this或super关键字。
    • 主函数是static,只能调用static方法。
    • 静态代码块随着类的加载而运行(只执行一次)。用于给类进行初始化。

    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:  
      10:     public static void main(String[] args) {
      11:         Thing thing1 = new Thing();
      12:         System.out.println("Hello, World!");
      13:     }
      14: }

    it refuses to compile. I get No enclosing instance of type Hello is accessible." at the line that creates a new Thing.

    A

    You've declared the class Thing as a non-static inner class. That means it must be associated with an instance of the Hello class.

    In your code, you're trying to create an instance of Thing from a static context. That is what the compiler is complaining about.

    There are a few possible solutions. Which solution to use depends on what you want to achieve.

    • Change Thing to be a static nested class.

         1: static class Thing
    • Create an instance of Hello, then create an instance of Thing.

         1: public static void main(String[] args)
         2: {
         3:     Hello h = new Hello();
         4:     Thing thing1 = h.new Thing(); // hope this syntax is right, typing on the fly :P
         5: }
    • Move Thing out of the Hello class.

  • 相关阅读:
    #include <utility>
    Html的空格显示
    ExtJs自学教程(1):一切从API開始
    天黑的时候,我又想起那首歌
    citrix协议ICA技术原理
    约瑟夫环问题
    数据结构和算法设计专题之---八大内部排序
    HDU
    深入分析C++引用
    八大排序算法总结
  • 原文地址:https://www.cnblogs.com/hust-ghtao/p/4644104.html
Copyright © 2011-2022 走看看