第七章課堂例子

來源:互聯網
上載者:User

標籤:

一、使用instanceof運算子判斷一個對象是否可以轉換為指定的類型:

      

public class TestInstanceof
{
public static void main(String[] args)
{
//聲明hello時使用Object類,則hello的編譯類型是Object,Object是所有類的父類
//但hello變數的實際類型是String
Object hello = "Hello";
//String是Object類的子類,所以返回true。
System.out.println("字串是否是Object類的執行個體:" + (hello instanceof Object));
//返回true。
System.out.println("字串是否是String類的執行個體:" + (hello instanceof String));
//返回false。
System.out.println("字串是否是Math類的執行個體:" + (hello instanceof Math));
//String實現了Comparable介面,所以返回true。
System.out.println("字串是否是Comparable介面的執行個體:" + (hello instanceof Comparable));
String a = "Hello";
//String類既不是Math類,也不是Math類的父類,所以下面代碼編譯無法通過
//System.out.println("字串是否是Math類的執行個體:" + (a instanceof Math));
}
}

   

二、類型轉換

 

子類可直接賦給基類(“基類變數=子類對象”);

基類的參考型別要傳遞給子類必須通過強制轉換(“子類變數=(子類名)基類對象”);

子類之間不可以進行轉換。

 

三、變態類


public class ParentChildTest {
public static void main(String[] args) {
Parent parent=new Parent();
parent.printValue();
Child child=new Child();
child.printValue();

parent=child;
parent.printValue();

parent.myValue++;
parent.printValue();

((Child)parent).myValue++;
parent.printValue();

}
}

class Parent{
public int myValue=100;
public void printValue() {
System.out.println("Parent.printValue(),myValue="+myValue);
}
}
class Child extends Parent{
public int myValue=200;
public void printValue() {
System.out.println("Child.printValue(),myValue="+myValue);
}
}

        當子類與父類擁有一樣的方法,並且讓一個父類變數引用一個子類對象時,到底調用哪個方法,由對象自己的“真實”類型所決定,

    這就是說:對象是子類型的,它就調用子類型的方法,是父類型的,它就調用父類型的方法。 這個特性實際上就是物件導向“多態”特

     性的具體表現。如果子類與父類有相同的欄位,則子類中的欄位會代替或隱藏父類的欄位,子類方法中訪問的是子類中的欄位(而不是

     父類中的欄位)。如果子類方法確實想訪問父類中被隱藏的同名欄位,可以用super關鍵字來訪問它。 如果子類被當作父類使用,則通

     過子類訪問的欄位是父類的。

四、

package test;


public class SystemExitAndFinally {

public static void main(String[] args)
{
try{

System.out.println("in main");
throw new Exception("Exception is thrown in main");
//System.exit(0);

}
catch(Exception e)
{
System.out.println(e.getMessage());
System.exit(0);
}
finally
{
System.out.println("in finally");
}
}

}

   JVM是java虛擬機器,finally是由JVM保證執行,而System.exit(0)是正常退出程式,結束JVM的運行,那麼最後finally就不再執行。

PS:System.exit(status)不管status為何值都會退出程式,非0,則表示為非正常退出程式,一般放在catch塊中,當捕獲到異常,需要

停止程式,用非0值來表示非正常退出程式

第七章課堂例子

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.