JDK8特性之默认方法

//一个接口有默认方法,考虑这样的情况,一个类实现了多个接口,
//且这些接口有相同的默认方法,以下实例说明了这种情况的解决方法:
public interface vehicle {
   default void print(){
      System.out.println("我是一辆车!");
   }
}
 
public interface fourWheeler {
   default void print(){
      System.out.println("我是一辆四轮车!");
   }
}
//第一个解决方案是创建自己的默认方法,来覆盖重写接口的默认方法:
public class car implements vehicle, fourWheeler {
   default void print(){
      System.out.println("我是一辆四轮汽车!");
   }
}
//第二种解决方案可以使用 super 来调用指定接口的默认方法:
public class car implements vehicle, fourWheeler {
   public void print(){
      vehicle.super.print();
   }
}

//Java 8 的另一个特性是接口可以声明(并且可以提供实现)静态方法
public interface vehicle {
   default void print(){
      System.out.println("我是一辆车!");
   }
    // 静态方法
   static void blowHorn(){
      System.out.println("按喇叭!!!");
   }
}
//该静态方法可直接调用
class Car implements Vehicle, FourWheeler {
   public void print(){
      Vehicle.super.print();
      FourWheeler.super.print();
      Vehicle.blowHorn();
      System.out.println("我是一辆汽车!");
   }
}
1.接口可以定义一个默认方法
2.接口可以定义静态方法

发表回复

您的电子邮箱地址不会被公开。

3 × 3 =