總網頁瀏覽量

2016年3月29日 星期二

[Java] instanceof 跟 static instanceof_static_test.java

instanceof_static_test.java

class A{
    static String name = "A";
    static String greeting(){
        return "Class A";
    }
}
public class instanceof_static_test extends A{
    static String name = "B";
    static String greeting(){
        return "Class B";
    }

    public static void main(String args[]){
        A a = new instanceof_static_test();
        System.out.println(a.name+", ");
        System.out.println(a.greeting());
       
        System.out.println();
       
        instanceof_static_test b = new instanceof_static_test();
        System.out.println(b.name+", ");
        System.out.println(b.greeting());       
    }
}

- - - - -
A,
Class A

B,
Class B
- - - - -

由上面程式碼來看,  一開始用A的觀點來建立instanceof_static_test物件,
而呼叫的name是類別層級的物件,
所以顯示出來的就會是A跟classA,
如果要顯示類別instanceof_static_test中的物件,
就要用instanceof_static_test來宣告.



沒有留言:

張貼留言