對象實例化過程: 1.看類是否已載入,未載入的話先初始化類。 2.在堆記憶體中分配空間。 3.初始化父類的屬性 4.初始化父類的構造方法 5.初始化子類的屬性 6.初始化子類的構造方法 實例: package com.xm.load; public class Animal { static Stri ...
對象實例化過程:
1.看類是否已載入,未載入的話先初始化類。
2.在堆記憶體中分配空間。
3.初始化父類的屬性
4.初始化父類的構造方法
5.初始化子類的屬性
6.初始化子類的構造方法
實例:
package com.xm.load;
public class Animal {
static String str = "I`m a animal!";
public String str1 = "I`m 10 years old @Animal";
static {
System.out.println(str);
System.out.println("載入父類靜態代碼塊");
}
static void doing() {
System.out.println("This ia a Animal!");
}
public Animal() {
doing();
System.out.println(str1);
System.out.println("Animal 對象實例化");
}
}
class Dog extends Animal{
static String str = "I`m a dog!";
private String str1 = "I`m 10 years old @Dog";
static {
System.out.println(str);
System.out.println("載入子類靜態代碼塊");
}
static void doing() {
System.out.println("This ia a dog!");
}
public Dog() {
doing();
System.out.println(str1);
System.out.println("Dog 對象實例化");
}
public static void main(String[] args) {
new Dog();
}
}
運行結果:
I`m a animal!
載入父類靜態代碼塊
I`m a dog!
載入子類靜態代碼塊
This ia a Animal!
I`m 10 years old @Animal
Animal 對象實例化
This ia a dog!
I`m 10 years old @Dog
Dog 對象實例化
我們來看一下,重寫過的父類方法,在載入父類時的情況。
實例:
package com.xm.load;
public class Animal {
static String str = "I`m a animal!";
public String str1 = "I`m 10 years old @Animal";
static {
System.out.println(str);
System.out.println("載入父類靜態代碼塊");
}
static void doing() {
System.out.println("This ia a Animal!");
}
public void todoing() {
System.out.println(str1);
System.out.println("載入子類的重寫方法");
}
public Animal() {
doing();
todoing();
System.out.println("Animal 對象實例化");
}
}
class Dog extends Animal{
static String str = "I`m a dog!";
private String str1 = "I`m 10 years old @Dog";
static {
System.out.println(str);
System.out.println("載入子類靜態代碼塊");
}
static void doing() {
System.out.println("This ia a dog!");
}
public void todoing() {
System.out.println(str1);
System.out.println("載入子類的重寫方法");
}
public Dog() {
doing();
System.out.println("Dog 對象實例化");
}
public static void main(String[] args) {
new Dog();
}
}
結果:
I`m a animal!
載入父類靜態代碼塊
I`m a dog!
載入子類靜態代碼塊
This ia a Animal!
null
載入子類的重寫方法
Animal 對象實例化
This ia a dog!
Dog 對象實例化
由此可見,null代表著載入父類構造方法時,調用的todoing( )方法是子類的方法,且子類的屬性的初始化過程發生在父類構造方法之後。