Java接口
接口可以理解为一个特殊的抽象类。
定义:
接口的定义方式与类有些相似,接口定义使用的关键字是 interface,接口定义的语法格式如下:
[public] interface interface_name [extends interface1_name[, interface2_name,…]] {
// 接口体,其中可以包含定义常量和声明方法
[public] [static] [final] type constant_name = value; // 定义常量
[public] [abstract] returnType method_name(parameter_list); // 声明方法
}
实现:
接口的主要用途就是被实现类实现,一个类可以实现一个或多个接口,继承使用 extends 关键字,实现则使用 implements 关键字。因为一个类可以实现多个接口,所以Java通过接口还是有多继承的。类实现接口的语法格式如下:
<public> class <class_name> [extends superclass_name] [implements interface1_name[, interface2_name…]] {
// 主体
}
看例子比较容易看懂:
例:创建一个名称为 InterfaceTest 的接口,具备求和和取最大值的方法:
package test;
public interface InterfaceTest {
public int sum();
public int getMAX(int a,int b);
}
//这样写在idea里会有一个警告:Modifier 'public' is redundant for interface methods
//java中接口的方法默认就是 public abstract 的,删掉public就行了,但如果改为protected 或者 private会报错。
通过implement来实现:
package test;
public class InterfaceIm implements InterfaceTest {
private int num1;
private int num2;
public InterfaceIm(int num1, int num2) { //构造函数
this.num1 = num1;
this.num2 = num2;
}
@Override
public int getMAX (int a, int b){
if (a >= b) {
return a;
} else {
return b;
}
}
public int sum (){
return num1 + num2;
}
public static void main (String[]args){
// 创建实现类的对象
InterfaceIm inter = new InterfaceIm ( 1, 3 );
System.out.println ( inter.sum () );
System.out.println ( inter.getMAX ( 2, 4 ) );
}
}
输出结果:
4
4
注意:一个接口可以有多个父接口,但接口只能继承接口,不能继承类。
Java小白修炼手册