博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
No enclosing instance of type Hello is accessible
阅读量:4605 次
发布时间:2019-06-09

本文共 1358 字,大约阅读时间需要 4 分钟。

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.

转载于:https://www.cnblogs.com/hust-ghtao/p/4644104.html

你可能感兴趣的文章
Jmeter测试dubbo接口填坑
查看>>
[zz]GDB调试精粹及使用实例
查看>>
数据库的创建和删除
查看>>
最简单的三层实例【插入据
查看>>
设计模式学习笔记——Prototype原型模式
查看>>
pom.xml里有红叉报错的解决办法
查看>>
Perl last和next的用法区别
查看>>
Selenium 管理 Cookies
查看>>
exceptionfunction[LeetCode]Permutations
查看>>
Linux(2)_常用命令2
查看>>
自定义分页
查看>>
[转]DELPHI——调试(1)
查看>>
JS秒数转成分秒时间格式
查看>>
xp_cmdshell 命令的开启与关闭,和状态查询
查看>>
Linux sudoers
查看>>
MySQL详解(18)-----------分页方法总结
查看>>
bzoj 4595 激光发生器
查看>>
multi cookie & read bug
查看>>
js时间转换
查看>>
(转载) Android Studio你不知道的调试技巧
查看>>