• Thinking in Java之衍生类和基础类的初始化顺序


    《Thinking in Java》书里的例子,我又稍微修改了下代码:

    class Real{
        public Real(String index) {
            // TODO Auto-generated constructor stub
            System.out.println("Real()"+index);
        }
    }
    class Meal{
        Real r= new Real("Meal");
        Meal() {
            // TODO Auto-generated constructor stub
            System.out.println("Meal()");
        }
    }
    class Bread{
        Bread() {
            // TODO Auto-generated constructor stub
            System.out.println("Bread()");
        }
    }
    class Cheese{
        Cheese() {
            System.out.println("Cheese()");
        }
    }
    class Lettuce{
        Lettuce() {
            // TODO Auto-generated constructor stub
            System.err.println("Lettuce()");
        }
    }
    class Lunch extends Meal{
        Real r= new Real("Lunch");
        Lunch(){
            System.out.println("Lunch()");
        }
    }
    class PortableLunch extends Lunch{
        Real r= new Real("PortableLunch");
        PortableLunch(){
            System.out.println("PortableLunch()");
        }
    }
    public class Sandwich extends PortableLunch{
        Bread b= new Bread();
        Cheese c= new Cheese();
        Lettuce l= new Lettuce();
        Sandwich(){
            System.out.println("Sandwich()");
        }
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            new Sandwich();
        }
    
    }

    output:


    Real()Meal
    Meal()
    Real()Lunch
    Lunch()
    Real()PortableLunch
    PortableLunch()
    Bread()
    Cheese()

    Lettuce()
    Sandwich()

    总结:

    如果衍生类和基础类都没有static成员,创建衍生类,初始化顺序:一直向上,从根类开始,初始化根类成员,然后根类构造器;然后向下,次根类成员,次根类构造器,以此类推,一直到衍生类本身。

    自己摸索的demo:

    package com.westward;
    
    public class Demo19 extends Animal{
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            System.out.println("Demo19.main();");
        }
    
    }
    class Animal{
        public static Good good= new Good(); 
    }
    class Good{
        public Good() {
            System.out.println("Good()");
        }
    }
    /*
     * 在继承中,如果衍生类有main方法,main方法中并未创建实例,加载顺序也是先加载基础类的static成员。然后衍生类的static成员,然后面方法。
     * 一句话,如果需要加载衍生类的类类型,即class,那么无论是创建此类的实例还是调用此衍生类的static方法(包括main方法),都会先去加载基础类,并初始化static成员。
     * */

    output:
    Good()
    Demo19.main();

  • 相关阅读:
    [java,2019-01-28] 枪手博弈,谁才是最后赢家
    [java,2019-01-25] 图片和二进制互转
    [java,2019-01-15] word转pdf
    [python,2018-06-29] 37%法则及其拓展解决恋爱问题
    [java,2018-06-26] 扑克牌抽牌求和问题
    [python,2018-06-25] 高德纳箭号表示法
    [java,2017-06-12] myEclipse双击无法打开文件
    OpenGL核心技术之法线贴图
    游戏中水的渲染技术系列一
    Unity 3D实现帧同步技术
  • 原文地址:https://www.cnblogs.com/westward/p/5329509.html
Copyright © 2020-2023  润新知