java - 默认方法和静态方法如何在 Java 8 接口(interface)中工作?

标签 java java-8 jls

我一直在努力了解 defaultstatic 方法在 java 8 中的实际工作原理?

考虑以下接口(interface):

public interface Car {

  default void drive() {
    System.out.println("Default Driving");
  }

  static int getWheelCount(){
    return wheelCount;
  }

  int wheelCount = 7;
}

和以下实现:

public class Benz implements Car { }

现在,如果我转到我的主要方法并编写:

public static void main(String[] args){
  Car car = new Benz();
  car.drive();
  System.out.println(Car.getWheelCount());
  System.out.println(Car.wheelCount);
}

我想知道引擎盖下到底发生了什么:

  1. 是否以类似于抽象类工作方式的方式在 Car 实例上调用默认方法?
  2. 语言需要哪些新功能/修改才能支持接口(interface)中的默认方法和静态方法?
  3. 我知道默认情况下,接口(interface)中的所有字段默认都是 public static final,这是否与我的上述问题有任何关系。
  4. 随着默认方法的引入,我们还需要抽象类吗?

附言
请随时编辑问题,使其对其他 SO 用户更有用。

最佳答案

  1. 是。

  2. Java 接口(interface)默认方法将帮助我们扩展接口(interface),而不必担心破坏实现类。

What if those computer-controlled car manufacturers add new functionality, such as flight, to their cars? These manufacturers would need to specify new methods to enable other companies (such as electronic guidance instrument manufacturers) to adapt their software to flying cars. Where would these car manufacturers declare these new flight-related methods? If they add them to their original interfaces, then programmers who have implemented those interfaces would have to rewrite their implementations. If they add them as static methods, then programmers would regard them as utility methods, not as essential, core methods.

  1. AFAIK,不需要覆盖静态方法,因此静态方法的final 是连贯的。重写取决于拥有一个类的实例。 静态方法 不与类的任何实例相关联,因此该概念不适用。但是,默认方法 必须具有我上面引用的可覆盖属性。

  2. 在 Java 8 的接口(interface)中可以有默认构造函数、私有(private)字段、实例成员吗?


我喜欢使用默认方法,

list.sort(ordering);

代替

Collections.sort(list, ordering);

关于java - 默认方法和静态方法如何在 Java 8 接口(interface)中工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46139234/

相关文章:

java - 合并 Map<String, List<String> Java 8 Stream

java - 在 for 循环中返回

java - Lambda表达式和方法重载疑惑

java - 为什么数组的元素为空?

java - GrailsParameterMap 在 Grails 中不可序列化

java - 从 HttpResponse 获取 ETAG 值

java - 在 Java 8 中使用Optional进行多次空值检查

java - REST ASSURED TEST 创建我自己的 given() 方法

java - 在同一个流上重复 forEach() - 为什么不可能?

java - 'T.super' 是 JLS 的合法表达吗?