[英]When we add two abstract methods in an interface and implement just one method then why can't we implement the other method using lambda?
[英]how can we implement methods in multiples classes if we add methods in interface
在采訪中,面試官問了這個問題。 在Interface1中有10個方法,實現Interface1有1000個類。 后來在Interface1中我添加了第11種方法。 如何在所有類中實現第11個方法。 后來他問你怎么能在幾節課中實現。 由於1000個課程,你不能只是去每個班級實施,而是花時間。 你能告訴我怎么解決嗎?
他可能暗示接口中的default
方法(僅適用於java 8
)。
例如:
interface MyInterface {
default void method() {
// do stuff...
}
}
實現接口的所有類都將繼承該方法,您可以在需要特定行為時覆蓋它。
class MyClass implements MyInterface {
@Override
public void method() {
// do stuff...
}
}
此外,您可以將基本方法留空(無效),然后在11個類中覆蓋它。 或者您可以使用另一個接口(例如: SubInterface
)擴展MyInterface
,覆蓋基本方法並使您的11個類直接實現SubInterface
以便它們繼承最具體的行為。 你提出的問題有很多可能性(包括抽象類,如評論中提到的那樣)。
如果你必須使用以前版本的Java,你可以簡單地使用抽象類,它是實現上述場景的一種方式。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.