溫馨提示×

java接口能不能被實(shí)例化如何解決

小億
191
2023-08-24 08:01:12
欄目: 編程語言

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

要解決這個問題,可以通過以下兩種方式來實(shí)例化接口:

  1. 創(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();
}
}
  1. 使用匿名內(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í)例化。

0