接口在JDK1.8之后(包括1.8)中的新特性:
接口中可以有:常量,抽象方法,静态方法,默认方法
说明:
1、如何调用接口中的静态方法:接口名.静态方法
2、如何调用接口中的默认方法:实现类的对象.默认方法名
3、类优先原则:一个类继承的父类和实现的接口(默认方法)中有同名同参的方法, 那么调用的是父类中的
4、接口冲突:一个类实现多个接口,多个接口(默认方法)中有同名同参的方法,这是就会发生接口冲突
5、解决接口冲突: 实现类只需要去重写该方法即可。再通过该类的对象调用此方法时调用的是重写的方法
6、实现类重写接口中的默认方法后,调用接口中的默认方法:接口名.super.默认方法名
7、如果使用抽象类和接口都可以的情况下,使用接口
interface MyInterface{
//静态方法
public static void info(){
System.out.println("MyInterface info");
}
//默认方法
default void show(){
System.out.println("MyInterface show");
}
}
interface MyInterface2{
//静态方法
public static void info(){
System.out.println("MyInterface2 info");
}
//默认方法
default void show(){
System.out.println("MyInterface2 show");
}
}
class SuperClass{
public void show(){
System.out.println("SuperClass show");
}
}
//如果一个类既要继承父类又要实现接口,那么继承放在实现的前面
class Myclass implements MyInterface,MyInterface2 {
@Override
public void show() {
System.out.println("MyClass show");
//需求:调用接口中的默认方法
MyInterface.super.show();
MyInterface2.super.show();
}
}
public class NewInterfaceTest {
public static void main(String[] args) {
//接口名.静态方法
MyInterface.info();
//实现类对象.默认方法名
new Myclass().show();
}
}