默认和静态方法如何在 java 8 个接口中工作?

How do default and static methods work in java 8 interfaces?

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

考虑以下接口:

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. 为了支持接口中的默认方法和静态方法,该语言需要哪些新的features/modifications?
  3. 我知道默认情况下,界面中的所有字段都是默认public static final,是否与我的上述问题有任何关系。
  4. 随着默认方法的引入,我们还需要抽象类吗?

P.S.
请随时编辑问题,使其对其他 SO 用户更有用。

看来您对抽象 class 和接口有点困惑。

摘要类:

在抽象classes中我们可以抽象方法和非抽象方法。对于抽象方法,我不需要有方法定义,对于非抽象方法,我们需要有方法体。

A class 仅在摘要 class 上扩展。

接口:

过去的接口(Java7)从来没有方法体,随着java8的出现我们可以用default关键字指定方法体。

一个class可以实现多个接口。

所以当我们需要一个class来符合两个实体的特性时,我们可能会利用接口。现在使用 default 关键字,我们为接口本身提供的 class 获得默认方法主体(接口方法的),我们可能会或可能不会选择覆盖并提供新的方法定义。

底线

使用接口还是抽象class完全看情况

  1. 是。

  2. Java 接口默认方法将帮助我们扩展接口而不用担心破坏实现 classes.

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静态方法是连贯的。覆盖取决于 class 的实例。 static 方法 与 class 的任何实例都没有关联,因此该概念不适用。但是,默认方法 必须具有可覆盖的 属性,正如我在上面引用的那样。

  2. 在Java8的接口中可以有默认构造函数、私有字段、实例成员吗?


我喜欢使用默认方法,

list.sort(ordering);

而不是

Collections.sort(list, ordering);