一旦从具体类实现接口,就需要为其所有方法提供实现。如果尝试在编译时跳过实现接口的方法,则会生成错误。示例 在线演示 interface MyInterface{ public void sample(); public void display(); } public class InterfaceExample implements MyInterface{ public void sample(){ System.out.println("Implementation of the sample method"); } public static void main(String args[]) { InterfaceExample obj = new InterfaceExample(); obj.sample(); } }编译时错误InterfaceExample.java:5: error: InterfaceExample is not abstract and does not override abstract method ... 阅读更多
Java 中的接口类似于类,但是它只包含抽象方法和字段,这些字段是 final 和 static 的。从 Java8 开始,静态方法和默认方法被引入到接口中。默认方法 - 与其他抽象方法不同,这些方法可以具有默认实现。如果接口中具有默认方法,则不必在已经实现此接口的类中重写(提供主体)它。简而言之,您可以使用实现类的对象访问接口的默认方法。示例 在线演示 interface MyInterface{ public static int num = ... 阅读更多
实际上你做不到,一旦你实现了接口,就必须为其所有方法提供实现,或者使类成为抽象类。如果没有实现(除非是默认方法),则无法跳过接口的方法。但是,如果您尝试跳过实现接口的方法,则会生成编译时错误。示例 在线演示 interface MyInterface{ public static int num = 100; public void sample(); public void getDetails(); public void setNumber(int num); public void setString(String data); } public class InterfaceExample implements MyInterface{ public static int num = 10000; public ... 阅读更多
抽象方法是没有主体的方法。它只包含一个带有分号的方法签名,在其前面有一个 abstract 关键字。public abstract myMethod();要使用抽象方法,您需要通过扩展其类并为其提供实现(主体)来继承它。如果类包含至少一个抽象方法,则必须将其声明为抽象类。示例 在线演示 import java.io.IOException; abstract class MyClass { public abstract void display(); } public class AbstractClassExample extends MyClass{ public void display(){ System.out.println("subclass implementation of the display method"); } public static void main(String ... 阅读更多