Default and static interface methods,
熟悉interface的大家應該都知道interface 只能定義"行為"不像是abstract class
除了定義行為之外還可以實作相關的內容,舉個最簡單的例子
這是我們熟悉的interface 只能定義"行為"

這是我們熟悉的abstract class 可以定義相關實作內容

不過這件事情在java8出現了改變
在java8 你可以針對interface 定義預設的行為,只要你不實作該功能,
他就會使用default的方法
如下,我針對DefaultInterface 定義了一個預設的getViewType行為

然後我並沒有在DefaultImp 裡面override getViewType這個method

所以當我new DefaultImp().getViewType()時會出現 DefaultInterface的 message
相對的假設我今天override了getViewType則message 會出現我override的方法
如下,假設我使用new CustomImp().getViewType則會出現 CustomImp的message

不過,這樣interface 和abstract的定義看起來就有點模糊了?
其實不會..
interface 還是只能定義"行為" CustomImp 並不能使用super.getViewType這種call 法
也不能定義field ,只能說interface的功能變強大了點!? 多了支援default 行為的這種功能
順道提一下現在interface 也可以定義static method了,不過這個看起來就跟原本的static method沒什麼太大差別,所以在這邊就不提了
android 上可以使用的java8 功能還有很多,會在之後再跟大家提到
沒有留言:
張貼留言