在new创建对象时,首先对对象属性和初始化块分配内存,并执行默认初始化。如果存在父类,则先为父类对象属性和初始化块先分配内存并执行初始化。然后执行父类构造器中的初始化程序,接着才开始对子类的对象属性和初始化块执行初始化。
我们修改一下代码,看一下继承的初始化顺序:
package com.ws.basic;
class GameObject{
int life;
public GameObject(int life) {
super();
this.life = life;
System.out.println("GameObject创建!");
}
public int life_reduce(int ai_reduce)
{
life = life - ai_reduce;
return life;
}
public int life_add(int ai_add)
{
life = life + ai_add;
return life;
}
}
class Creature extends GameObject {
String mc;
int attack;
public Creature(String mc, int attack,int life) {
super(life);
this.mc = mc;
this.attack = attack;
System.out.println("creature创建!");
}
public void move() {
System.out.println(mc+"在移动!");
}
public void normal_attack() {
System.out.println(mc+"在普通攻击!");
}
}
class Hero extends Creature{
String name;
String skill;
public Hero(String name,String skill,String mc, int attack,int life) {
super(mc,attack,life);
this.name = name;
this.skill = skill;
System.out.println("hero创建!");
}
// 重写普通攻击方法
public void normal_attack(){
System.out.println(mc + name + "用火球攻击!");
}
public void skill_attack(){
System.out.println(mc + name + "用"+skill+"攻击!");
}
public void eat_food(int food){
life_add(food);
System.out.println(mc + name + "吃了"+food + "血,当前血量"+life);
}
}
public class testjc {
public static void main(String[] args) {
Hero heroDfs = new Hero("甘道夫","暴风雪","大法师",14,450);
heroDfs.normal_attack();
}
}
执行:
GameObject创建!
creature创建!
hero创建!
大法师甘道夫用火球攻击!
结论:
通过代码的执行,我们可以清晰的了解继承时候的初始化顺序,系统首先初始化了GameObject,然后初始化了creature,接着初始化了hero。所以,对于一个问题加深理解最好的方法,就是写段代码,测试一下。