当前位置:编程学习 > JAVA >>

Java中类的执行顺序详解

本文讲解Java中类的执行顺序
顺序应该是这样的:父类Static->子类static->父类缺省{}->父类构造函数->子类缺省{}->子类构造函数
所以上面的例子打印顺序应该是这样的:
parent static block 父类Static
child static block 子类static
parent  block 父类缺省{}
parent constructor 父类构造函数
child  block子类缺省{}
child constructor子类构造函数
class Parent{
     static String name = "hello";
     static {
         System.out.println("parent static block");
     }
     {
         System.out.println("parent block");
     }
     public Parent(){
         System.out.println("parent constructor");
     }
 }
   
 class Child extends Parent{
     static String childName = "hello";
     static {
         System.out.println("child static block");
     }
     {
         System.out.println("child block");
     }
     public Child(){
         System.out.println("child constructor");
     }
 }
   
 public class StaticIniBlockOrderTest {
   
     public static void main(String[] args) {
         new Child();//语句(*)

     }
 }
补充:软件开发 , Java ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,