Java接口的目的是什么?
Java中的接口是方法原型的规范。每当您需要指导程序员或订立合同以指定应如何使用类型的方法和字段时,都可以定义接口。
要创建这种类型的对象,您需要实现此接口,为接口的所有抽象方法提供主体,并获取实现类的对象。
接口的所有方法都是公共的和抽象的,我们将使用interface关键字定义一个接口,如下所示-
interface MyInterface{ public void display(); public void setName(String name); public void setAge(int age); }
接口用途
提供通信-接口的用途之一是提供通信。通过接口,您可以指定想要特定类型的方法和字段的方式。
多重继承 -Java不支持多重继承,使用接口可以实现多重继承-
示例
interface MyInterface1{ public static int num = 100; public default void display() { System.out.println("display method of MyInterface1"); } } interface MyInterface2{ public static int num = 1000; public default void display() { System.out.println("display method of MyInterface2"); } } public class InterfaceExample implements MyInterface1, MyInterface2{ public void display() { System.out.println("This is the implementation of the display method"); } public void show() { MyInterface1.super.display(); MyInterface2.super.display(); } public static void main(String args[]) { InterfaceExample obj = new InterfaceExample(); obj.show(); } }
输出结果
display method of MyInterface1 display method of MyInterface2
抽象-抽象是向用户隐藏实现细节的过程,只有功能会提供给用户。换句话说,用户将获得有关对象做什么而不是对象如何工作的信息。
由于接口的所有方法都是抽象的,因此用户只知道方法签名/原型,否则不知道该如何编写方法。使用接口,您可以实现(完整)抽象。
松散耦合-耦合是指一种对象类型对另一种对象的依赖性,如果两个对象彼此完全独立,并且在一个对象中所做的更改不会影响另一个对象,则称这两个对象为松散耦合。
您可以使用接口在Java中实现松散耦合-
示例
interface Animal { void child(); } class Cat implements Animal { public void child() { System.out.println("kitten"); } } class Dog implements Animal { public void child() { System.out.println("puppy"); } } public class LooseCoupling{ public static void main(String args[]) { Animal obj = new Cat(); obj.child(); } }
输出结果
kitten