2007最后一套JAVA面試題(繼承)
繼承時候類的執行順序問題,一般都是選擇題,問你將會打印出什么?
package com.test;

public class Parent
{
//1
static int a = 1;
//2
static
{
a = 10;
System.out.println("parent static code");
}
//4
public Parent()
{
System.out.println("Parent constructor");
System.out.println("Parent a=" + a);
}
public static void main(String[] args)
{
System.out.println("***************");
Parent c = new Child();
}
}

class Child extends Parent
{
static int a = 2;
//3
static
{
a = 20;
System.out.println("child static code");
}
//5
public Child()
{
System.out.println("Child constructor");
System.out.println("Child var a=" + a);
}
}
輸出結果:
parent static code
child static code
***************
Parent constructor
Parent a=10
Child constructor
Child var a=20
由此可看出在還沒有實例化類的時候(注意*號)已經執行了static代碼塊。
順序是先父類后子類.
然后才調用父類的構造方法,再調用子類的構造方法.就是這個順序了.
package com.test;

public class Parent
{
//1
static int a = 1;
//2
static
{
a = 10;
System.out.println("parent static code");
}
//4
public Parent()
{
System.out.println("Parent constructor");
System.out.println("Parent a=" + a);
}
public static void main(String[] args)
{
System.out.println("***************");
Parent c = new Child();
}
}

class Child extends Parent
{
static int a = 2;
//3
static
{
a = 20;
System.out.println("child static code");
}
//5
public Child()
{
System.out.println("Child constructor");
System.out.println("Child var a=" + a);
}
}












































輸出結果:








由此可看出在還沒有實例化類的時候(注意*號)已經執行了static代碼塊。
順序是先父類后子類.
然后才調用父類的構造方法,再調用子類的構造方法.就是這個順序了.












































posted on 2007-12-28 10:36 々上善若水々 閱讀(2752) 評論(7) 編輯 收藏 所屬分類: Java筆試與面試