被static关键字修饰的方法或者变量不需要依赖于对象来进行访问,只要类被加载了,就可以通过类名去进行访问。static是不允许用来修饰局部变量。

问题来了,带有static关键字的类,执行的先后顺序是什么呢?先看几个例子。

一、下面这段代码的输出结果是什么?

public class Test extends Base{
    static{
        System.out.println("test static");
    }
    public Test(){
        System.out.println("test constructor");
    } 
    public static void main(String[] args) {
        new Test();
    }
}
class Base{
    static{
        System.out.println("base static");
    }
    public Base(){
        System.out.println("base constructor");
    }
}
base static
test static
base constructor
test constructor
View Code

相关文章:

  • 2022-01-20
  • 2022-02-09
  • 2022-02-16
  • 2021-07-22
  • 2022-12-23
  • 2021-10-19
  • 2021-09-30
  • 2021-09-12
猜你喜欢
  • 2021-09-11
  • 2021-07-28
  • 2021-06-10
  • 2021-05-03
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案