继承与多态的理解
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一个对象时,静态代码块会重新加载一次。