static

static是什么?

Static是java里的一个非访问修饰符(Non Access Modifier),可以被用在变量,方法,嵌套类和静态block上。

1. 静态变量

  • 静态变量只在class loading时被分配一次内存。
  • 所有类的实例共享一份静态变量的拷贝,访问静态变量时可直接用<<ClassName>>.<<VariableName>>无需建立实例。
  • 静态变量的值对于所有该类实例是共用的。
  • 局部变量前不能加static,否则会抛出"illegal start of expression"

As static variables are available for the entire class so conceptually it can only be declared after the class whose scope is global where as static block or methods all have their own scope.

但是这在c/c++中是允许的
From wikipedia:

"Static local variables: variables declared as static inside inside a function are statically allocated while having the same scope as automatic local variables. Hence whatever values the function puts into its static local variables during one call will still be present when the function is called again."

2. 静态方法

  • 静态方法属于类而不是类的实例,可以直接用<<ClassName>>.<<MethodName>>调用。
  • 静态方法只能访问静态变量。只能调用静态方法。
  • 静态方法中只有main()会被JVM自动调用。

3. 静态方法能否被重载

, Read More..

4. 静态方法能否被覆盖

不能, 因为JAVA里不会有 Run-time Polymorphism. Read More..

5. 为什么main()方法要是静态的

因为如果main方法不是静态的,要先实例化对象才能调用main,会需要额外的内存分配。

6. 静态块

  • 静态块是类第一次被加载进JVM时会执行的一段代码。大多情况用来初始化变量。
  • 静态块只会在加载时被调用过一次,不能有返回类型或关键词(this,super)。
  • 可以有多个静态块,执行顺序同写的顺序。

7. 静态类

  • 只有嵌套类可以被声明为static,顶层类不行。
  • Even though static classes are nested inside a class, they doesn’t need the reference of the outer class they act like outer class only. Read More..

8. 构造函数可以是static的吗?

不能,会报错“modifier static not allowed here”

  • 如果构造函数是static,那么子类无法继承,违背了JAVA继承的目的。
  • 构造函数是与一个实例相关的,声明成static无意义。

8. 为什么抽象方法不能是static的?

抽象方法不能被调用,而static方法可直接被调用,矛盾。

9. interface中不能有static方法

因为接口中所有方法是隐式abstract的。

10. abstract类可以有static方法吗

可以。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,256评论 19 139
  • static表示“全局”或者“静态”的意思,用来修饰成员变量和成员方法,也可以形成静态static代码块,但是Ja...
    安安静静写代码阅读 9,643评论 1 7
  • 文章大纲:1.为什么static会有这样的效果?2.static的使用3.static误区4.static面试题 ...
    柠檬乌冬面阅读 5,927评论 3 43
  • final final类 final类不能被继承,因此final类的成员方法没有机会被覆盖,默认都是final的。...
    吃瓜群众liu阅读 347评论 0 1
  • 邻居是一个十五六岁的挺古怪女孩,我见她拖一只大箱子很费力的模样,忍不住主动向她伸出援手:“我帮你吧,箱子也...
    骨头兔子阅读 2,197评论 4 3