Object obj="hello";
上面的obj是什么類型?
object?NO!String?NO?
答案:編譯階段是Object類型,而在運行階段是String類型。實際上obj是String類型。只不過分為編譯和運行兩個部分!
那為什么會發生這種情況呢?
我們知道:對於Object obj而言,程序聲明了一個Object類型的變量!
而“hello”是一個String類型的對象
將Object類型的變量只想String類型的對象,由上篇可以看出這是一個上轉型類型!變量由String類型轉到Object類型!
由上轉型的知識我們知道,在運行期間,對象是直接調用子類String中的方法(但是變量仍然是調用父類中的變量)
我們必須清楚這種引用類型的強制類型轉化是非常危險的
如: Object obj="hello"; Integer in=obj;
這也就引出了如何避免強制引用類型轉化的問題:在java中我們用instanceof 來判斷一個引用類型是否可以轉化到其他類型
instanceof 用於判斷某個對象是否是一個類或則子類,實現類,接口的實例,如果是 則返回true,如何不是則返回false
例子:
public static void main(String[] args) { // TODO Auto-generated method stubs Object hello="hello"; //hello運行時就是String類型:true System.out.println((hello instanceof String)); //hello運行時String類型,而String類型是Object類型的子類,子類上轉型:true System.out.println((hello instanceof Object)); //String 類型和Math類型風馬牛不相及:false System.out.println((hello instanceof Math)); //String 類型也是Comparable類型的子類:true System.out.println((hello instanceof Comparable)); //Integet是Object的子類 Integer inte=new Integer(7); System.out.println(inte instanceof Object); //不能下轉型:false Object object=new Object(); System.out.println("object is Integer:"+(object instanceof Integer)); Integer k=10; if((k instanceof Object)) { object=k; //可以執行,因為k就是一個Integer類型,而Integer類型是Object類型的一個子類,符合上轉型 } //通Object o="sf"; Object o=7; System.out.println(o instanceof Integer); }