zoukankan      html  css  js  c++  java
  • 继承与多态的理解


    public class Base {

    public static int s;
    private int a ;

    static
    {
    System.out.println("基类静态代码块,s:"+s);
    }

    {
    System.out.println("基类实例代码快,a:"+a);

    }

    public Base()
    {
    System.out.println("基类构造方法,a:"+a);
    a=2;
    }

    protected void step()
    {
    System.out.println("base ,s:"+s + ",a:"+ a);

    }

    public void action()
    {
    System.out.println("start");
    step();
    System.out.println("end");


    }
    }


    public class Base {

    public static int s;
    private int a ;

    static
    {
    System.out.println("基类静态代码块,s:"+s);
    }

    {
    System.out.println("基类实例代码快,a:"+a);

    }

    public Base()
    {
    System.out.println("基类构造方法,a:"+a);
    a=2;
    }

    protected void step()
    {
    System.out.println("base ,s:"+s + ",a:"+ a);

    }

    public void action()
    {
    System.out.println("start");
    step();
    System.out.println("end");


    }
    }


    public class Child extends Base{

    public static String s;
    private int a;

    static
    {
    System.out.println("子类静态代码快,s:"+s);
    }

    {
    System.out.println("子类实例代码快,a:"+a);
    a=10;

    }

    public Child()
    {
    System.out.println("子类构造方法:a:" + a);
    a = 20;
    }

    protected void step()
    {
    System.out.println("Child ,s:"+s + ",a:"+ a);
    }

    public static void main (String[] args)
    {
    System.out.println("---new Child()---begin");
    Child child = new Child();
    System.out.println("---new Child()----end --");

    System.out.println("\n---child.action()");
    child.action();

    Base base = child ;
    System.out.println("\n---base.action()");
    base.action();

    System.out.println("\n---base.s" + base.s);
    System.out.println("\n---child.s" + child.s);

    }

    }

    执行结果为:

    基类静态代码块,s:0
    子类静态代码快,s:null
    ---new Child()---begin
    基类实例代码快,a:0
    基类构造方法,a:0
    子类实例代码快,a:0
    子类构造方法:a:10
    ---new Child()----end --

    ---child.action()
    start
    Child ,s:null,a:20
    end

    ---base.action()
    start
    Child ,s:null,a:20
    end

    ---base.s0

    ---child.snull

    执行顺序为:

     基类静态代码块 >> 子类静态代码快  >>  基类实例代码快  >>  基类构造方法  >>  子类实例代码快 >>  子类构造方法 

    且静态代码块只加载一次,是在加载类的时候加载的。每new一个对象时,静态代码块会重新加载一次。

  • 相关阅读:
    工作笔记(一)
    如何修改mindmanager默认字体为微软雅黑
    彻底解决zend studio 下 assignment in condition警告
    PHP5.2至5.6的新增功能详解
    ThinkPHP中的模型命名
    12大网站建设技巧 让访客信任你
    CentOS 7.0编译安装Nginx1.6.0+MySQL5.6.19+PHP5.5.14
    几种不错的编程字体
    大型网站的灵魂——性能
    MySQL: InnoDB 还是 MyISAM?
  • 原文地址:https://www.cnblogs.com/huoqm/p/6122988.html
Copyright © 2011-2022 走看看