Java 中实例方法、静态代码块和构造函数的执行顺序是什么?


静态代码块是一个带有 static 关键字的代码块。一般来说,这些用于初始化类的静态成员变量。JVM 在加载类时在 main 方法之前执行静态代码块。

示例

public class MyClass {
   static{
      System.out.println("Hello this is a static block");
   }
   public static void main(String args[]){
      System.out.println("This is main method");
   }
}

输出

Hello this is a static block
This is main method

构造函数类似于方法,它在创建类的对象时被调用,通常用于初始化类的实例变量。构造函数的名称与它们的类相同,并且没有返回类型。

public class MyClass {
   MyClass(){
      System.out.println("Hello this is a constructor");
   }
   public static void main(String args[]){
      new MyClass();
   }
}

输出

Hello this is a constructor

实例方法

这些是类的普通方法(非静态),你需要使用类的对象来调用它们 −

示例

public class MyClass {
   public void demo(){
      System.out.println("Hello this is an instance method");
   }
   public static void main(String args[]){
      new MyClass().demo();
   }
}

输出

Hello this is an instance method

执行顺序

当在一个类中同时有这三者时,首先执行静态代码块,然后是构造函数,最后是实例方法。

示例

public class ExampleClass {
   static{
      System.out.println("Hello this is a static block");
   }
   ExampleClass(){
      System.out.println("Hello this a constructor");
   }
   public static void demo() {
      System.out.println("Hello this is an instance method");
   }
   public static void main(String args[]){
      new ExampleClass().demo();
   }
}

输出

Hello this is a static block
Hello this a constructor
Hello this is an instance method

更新于: 2020-07-02

7K+ 浏览

开启你的 事业

完成课程即可获得认证

开始
广告
© . All rights reserved.