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

  • 相关阅读:
    掌握 bind, apply 和 call 的用法
    导航页
    SSIS连接Oracle数据源
    redhat6.4 配置centos6 yum替换
    java web程序 上机考试做一个登陆注册程序
    java web程序 jdbc连接数据库错误排查方法
    java web程序 上机考试登陆界面设计实现
    java web 程序---缓冲代码
    java web程序 String的valueOf方法总集
    java web程序 登陆验证页面 4个页面人性化设置
  • 原文地址:https://www.cnblogs.com/huoqm/p/6122988.html
Copyright © 2011-2022 走看看