美文网首页
面试题-代码执行顺序

面试题-代码执行顺序

作者: Eve0 | 来源:发表于2020-10-20 16:35 被阅读0次

    例1

    public class LeafTest {
    
        public static void main(String[] args) {
            new Leaf();
        }
    }
    
    class Root{
        static {
            System.out.println("root static block");
        }
    
        {
            System.out.println("root block");
        }
        Root(){
            System.out.println("root default constructor");
        }
    }
    class Mid extends Root{
        static {
            System.out.println("Mid static block");
        }
    
        {
            System.out.println("Mid block");
        }
        Mid(){
            System.out.println("Mid default constructor");
        }
    }
    class Leaf extends Mid{
        static {
            System.out.println("Leaf static block");
        }
    
        {
            System.out.println("Leaf block");
        }
        Leaf(){
            System.out.println("Leaf default constructor");
        }
    }
    

    显示结果

    root static block
    Mid static block
    Leaf static block
    root block
    root default constructor
    Mid block
    Mid default constructor
    Leaf block
    Leaf default constructor
    
    

    先父类,后子类。静态先行

    例2

    public class A extends B{
        static {
            System.out.println("1111");
        }
        {
            System.out.println("2222");
        }
        A(){
            System.out.println("3333");
        }
        public static void main(String[] args) {
            System.out.println("4444");
    
            System.out.println("#####");
            new A();
            System.out.println("$$$$");
            new A();
            System.out.println("****");
            new B();
        }
    }
    class B{
        static {
            System.out.println("5555");
        }
        {
            System.out.println("6666");
        }
        B(){
            System.out.println("7777");
        }
    
    }
    

    显示结果

    5555
    1111
    4444
    #####
    6666
    7777
    2222
    3333
    $$$$
    6666
    7777
    2222
    3333
    ****
    6666
    7777
    

    相关文章

      网友评论

          本文标题:面试题-代码执行顺序

          本文链接:https://www.haomeiwen.com/subject/clvdmktx.html