在实现Java接口时,能否只覆盖一个方法?
Java中的接口是方法原型的规范。无论何时你需要指导程序员,或者制定一个合同来指定类型的行为(方法和字段),你都可以定义一个接口。
要创建此类型的对象,你需要实现此接口,为接口的所有抽象方法提供主体,并获取实现类的对象。
示例
interface Sample { void demoMethod1(); void demoMethod2(); void demoMethod3(); } public class InterfaceExample implements Sample { public void demoMethod1() { System.out.println("This is demo method-1"); } public void demoMethod2() { System.out.println("This is demo method-2"); } public void demoMethod3() { System.out.println("This is demo method-3"); } public static void main(String args[]) { InterfaceExample obj = new InterfaceExample(); obj.demoMethod1(); obj.demoMethod1(); obj.demoMethod3(); } }
输出
This is demo method-1 This is demo method-2 This is demo method-3
在实现接口时,必须覆盖所有抽象方法,如果跳过覆盖任何抽象方法,则会生成编译时错误。
示例
interface Sample { void demoMethod1(); void demoMethod2(); void demoMethod3(); } public class InterfaceExample implements Sample { public void demoMethod1() { System.out.println("This is demo method-1"); } public void demoMethod2() { System.out.println("This is demo method-2"); } public static void main(String args[]) { InterfaceExample obj = new InterfaceExample(); obj.demoMethod1(); obj.demoMethod2(); } }
输出
InterfaceExample.java:6: error: InterfaceExample is not abstract and does not override abstract method demoMethod3() in Sample public class InterfaceExample implements Sample{ ^ 1 error
但是,如果你只想覆盖一个抽象方法 -
你可以将其余方法保持未实现,如下所示 -
示例
interface Sample { void demoMethod1(); void demoMethod2(); void demoMethod3(); } public class InterfaceExample implements Sample { public void demoMethod1() { System.out.println("This is demo method-1"); } public void demoMethod2() { } public void demoMethod3() { } public static void main(String args[]) { InterfaceExample obj = new InterfaceExample(); obj.demoMethod1(); obj.demoMethod2(); obj.demoMethod3(); } }
输出
This is demo method-1
由于不必强制实现接口的默认方法,你可以将其余方法声明为默认,如下所示 -
示例
interface Sample { void demoMethod1(); default void demoMethod2() { System.out.println("Default demo method 2"); } default void demoMethod3() { System.out.println("Default demo method 3"); } } public class InterfaceExample implements Sample { public void demoMethod1() { System.out.println("This is demo method-1"); } public static void main(String args[]) { InterfaceExample obj = new InterfaceExample(); obj.demoMethod1(); obj.demoMethod2(); obj.demoMethod3(); } }
输出
This is demo method-1 Default demo method 2 Default demo method 3
广告