您现在的位置是:首页 > 文章详情

Java中Static执行顺序

日期:2018-08-11点击:358

Java中Static执行顺序

什么是static

static方法就是没有this的方法。在static方法内部不能调用非静态方法,反过来是可以的。而且可以在没有创建任何对象的前提下,仅仅通过类本身来调用static方法。也就是说说被static关键字修饰的方法或者变量不需要依赖于对象来进行访问,只要类被加载了,就可以通过类名去进行访问

static代码块

static关键字还有一个比较关键的作用就是用来形成静态代码块以优化程序性能。static块可以置于类中的任何地方,类中可以有多个static块。在类初次被加载的时候,会按照static块的顺序来执行每个static块,并且只会执行一次。 

static方法

静态方法可以直接通过类名调用,任何的实例也都可以调用, 因此静态方法中不能用this和super关键字,不能直接访问所属类的实例变量和实例方法(就是不带static的成员变量和成员成员方法),只能访问所属类的静态成员变量和成员方法。

static变量

按照是否静态的对类成员变量进行分类可分两种:一种是被static修饰的变量,叫静态变量或类变量;另一种是没有被static修饰的变量,叫实例变量

static 执行顺序

如果不继承别的类,那么执行顺序应该是: 
static代码块–>普通代码块–>类构造方法 
如果继承了别的类,那么执行顺序应该是: 
父类static代码块–>子类static代码块–>父类普通代码块–>父类构造方法–>子类普通代码块–>子类构造方法 
下面直接上代码

父类Animal

public class Animal { static { System.out.println("This is Animal Static area Code... "); } { System.out.println("This is Animal General area Code..."); } //static String constant; public Animal() { System.out.println("This is Animal Construct Method..."); } public void running() { System.out.println("I'm Running"); } } 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23

子类Dog

public class Dog extends Animal { static { System.out.println("This is Dog Static area Code..."); } { System.out.println("This is Dog General area Code..."); } public Dog(){ System.out.println("This is Dog Construct Method..."); } }  
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

模拟调用

public class Client { public static void main(String[] args){ Dog dog = new Dog(); dog.running(); } } 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

执行结果

This is Animal Static area Code... This is Dog Static area Code... This is Animal General area Code... This is Animal Construct Method... This is Dog General area Code... This is Dog Construct Method... I'm Running
原文链接:https://yq.aliyun.com/articles/624369
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章