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小白修煉手冊