Java接口本身不能被實(shí)例化,因?yàn)榻涌谑浅橄蟮?,它只能定義方法的聲明,而沒有具體的實(shí)現(xiàn)。接口只能被類實(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();
}
}
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í)例化。