接口定义语法规则:
public interface 接口名{
常量
抽象方法
默认方法 //JAVA8
静态方法 //JAVA8
私有方法 //JAVA9
}
示例:演示Java8之后接口的用法
- 接口:
public interface NewInter {
int PAGE_SIZE = 1234;
void fun1();
//默认方法
default void fun2(){
System.out.println("fun2");
}
//接口中的静态方法只能通过接口名调用
static void fun3(){
System.out.println("fun3");
}
//私有方法
private void fun4() {
System.out.println("fun4");
}
}
- 实现类:
public class NewClass implements NewInter {
@Override
public void fun1() { //实现接口中的抽象方法
}
@Override
public void fun2() {//重写接口中的默认方法
}
}
- 测试代码:
public static void main(String[] args) {
NewClass obj = new NewClass();
obj.fun1();
obj.fun2();
NewInter.fun3();
System.out.println(NewInter.PAGE_SIZE);
}