2019-03-27面試

今天遇到一個面試,順便學習加深印象,分享給大家……

System.identityHashCode方法是java根據對象在內存中的地址算出來的一個數值,不同的地址算出來的結果是不一樣的。
1、一個接口中有一個變量,2個類實現這個接口,實現類中的接口中的這個變量地址一樣嗎?

public interface MyInterFace {
    String str = "1111";
}
public class One  implements MyInterFace {
}
public class Two implements MyInterFace {
}

public class Main {
    public static void main(String[] args) {
        One one = new One();
        Two two = new Two();

        System.out.println(System.identityHashCode(one.str));
        System.out.println(System.identityHashCode(two.str));
    }
}

結論:一樣的且不能修改 因爲接口中的變量默認是final,public 修飾

-----------1----------
356573597
356573597
-----------------------

2、一個父類有一個變量,2個子類繼承父類,那麼這個父類中的變量地址一樣?

public class MyClass {
    String obj = "22223";
}
public class One extends MyClass{
}
public class Two extends MyClass{
}
public class Main {
    public static void main(String[] args) {
        One one = new One();
        Two two = new Two();
        System.out.println("-----------2----------");
        System.out.println(System.identityHashCode(one.obj));
        System.out.println(System.identityHashCode(two.obj));
        System.out.println("---------------------");
    }
}

結論:因爲是public的 是一樣的額,且可以修改

-----------2----------
1735600054
1735600054
---------------------

3、一個父類中有構造方法、靜態方法;一個子類有構造方法,靜態方法,執行順序是什麼?

//父類
public class Three {
    public Three() {
        System.out.println("父類構造");
    }
    public static void go(){
        System.out.println("父類靜態方法");
    }
}

public class ThreeSun extends Three {
    public ThreeSun() {
        System.out.println("子類構造方法");
    }

    public static void go() {
        System.out.println("子類靜態方法");
    }
}

結論:先執行父類的,再執行子類的,父類的go()被子類屏蔽了

父類構造
子類構造方法
子類靜態方法

4、直接new2個變量 和讓2個變量等於一個常量 ,變量地址一樣嗎?

        String a = new String("1");
        String b = new String("1");

        String c = "1";
        String d = "1";

        System.out.println("-----------3----------");
        System.out.println(System.identityHashCode(a));
        System.out.println(System.identityHashCode(b));

        System.out.println(System.identityHashCode(c));
        System.out.println(System.identityHashCode(d));

結論:

-----------4----------
356573597
1735600054
21685669
21685669
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章