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一个对象时,静态代码块会重新加载一次。

  • 相关阅读:
    没有纳入spring管理的类如何注入spring管理的对象
    Servlet里面url-pattern的通配符*的使用规则
    【转】request和response的页面跳转传参
    Mybatis-Generator逆向生成Po,Mapper,XMLMAPPER(一)
    Sae上传war包找不到编译文件
    Maven配置中scope说明
    Spring配置中的classpath和classpath*的区别
    国内的ntp服务器
    U盘拷贝文件大小有限制吗?
    Genymotion安装教程
  • 原文地址:https://www.cnblogs.com/huoqm/p/6122988.html
Copyright © 2011-2022 走看看