共計 579 個字符,預(yù)計需要花費(fèi) 2 分鐘才能閱讀完成。
Java 接口本身不能被實(shí)例化,因?yàn)榻涌谑浅橄蟮模荒芏x方法的聲明,而沒有具體的實(shí)現(xiàn)。接口只能被類實(shí)現(xiàn)。
要解決這個問題,可以通過以下兩種方式來實(shí)例化接口:
- 創(chuàng)建一個實(shí)現(xiàn)了該接口的類的實(shí)例對象。
interface MyInterface {void myMethod();
}
class MyClass implements MyInterface {
@Override
public void myMethod() {// 方法的具體實(shí)現(xiàn)}
}
public class Main {public static void main(String[] args) {MyInterface myObject = new MyClass();
myObject.myMethod();}
}
- 使用匿名內(nèi)部類的方式來實(shí)現(xiàn)接口的實(shí)例化。
interface MyInterface {void myMethod();
}
public class Main {public static void main(String[] args) {MyInterface myObject = new MyInterface() {
@Override
public void myMethod() {// 方法的具體實(shí)現(xiàn)}
};
myObject.myMethod();}
}
在以上兩種方式中,都是通過創(chuàng)建一個實(shí)現(xiàn)了接口的類的實(shí)例對象來實(shí)現(xiàn)接口的實(shí)例化。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完