Re: [問題] 不太懂怎麼把母class轉型成子class
你要問的應該是所謂的 downcast
Java 語法上使用一般的 cast 即可 (就是前面擺一對括號裡面放型態)
不過當來源跟目標都是 reference 型態且這兩種型態間沒有上下繼承關係的話
javac 會 compile error 告訴你無論如何這都轉不過去
如果是 upcast (轉成父類別) 那什麼事都沒有
(事實上 upcast 可以隱式進行, 這也是你已經在程式裡做過的)
downcast 時編譯會過, 但如果實際上轉不過去的話會扔 ClassCastException 出來
所以你其實只需要用普通的 cast 語法即可
如果要寫的小心一點就外面包個 try/catch 接 ClassCastException 處理錯誤狀況
要不然就是用 instanceof 先檢查那確實是你要的類別再轉
--
'You've sort of made up for it tonight,' said Harry. 'Getting the
sword. Finishing the Horcrux. Saving my life.'
'That makes me sound a lot cooler then I was,' Ron mumbled.
'Stuff like that always sounds cooler then it really was,' said
Harry. 'I've been trying to tell you that for years.'
-- Harry Potter and the Deathly Hollows, P.308
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 123.195.39.85
※ 文章網址: http://www.ptt.cc/bbs/java/M.1416727469.A.725.html
※ 編輯: LPH66 (123.195.39.85), 11/23/2014 15:24:56
→
11/23 19:31, , 1F
11/23 19:31, 1F
→
11/23 19:31, , 2F
11/23 19:31, 2F
→
11/25 00:55, , 3F
11/25 00:55, 3F
討論串 (同標題文章)
完整討論串 (本文為第 2 之 2 篇):