本文介绍了默认和静态方法如何在Java 8接口中工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在努力弄清默认静态方法在Java 8中的实际工作方式是什么?

I have been trying to get my head around on how actually do the default and static methods work in 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 { }

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

Now if I go to my main method and write:

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

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

I would like to know what is really going on under the hood:

  1. 是否以类似于抽象类工作方式的方式在Car实例上调用默认方法?
  2. 为了在接口中支持默认和静态方法,该语言需要哪些新功能/修改?
  3. 我知道默认情况下,界面中的所有字段默认情况下都是public static final,无论如何与我上面的问题有关.
  4. 通过引入默认方法,我们是否不再需要抽象类?
  1. Does the default method get called upon the instance of Car in a way which is similar to how abstract classes work?
  2. What new features/modifications did the language need in order to support default and static methods in interfaces?
  3. I know that by default, all the fields in an interface are by default public static final, is that in any way related to my above questions.
  4. With the introduction of default methods, do we have the need of abstract classes anymore?

PS
请随时编辑问题,以使其对其他SO用户更加有用.

P.S.
Please feel free to edit the question to make it more useful for fellow SO users.

推荐答案

  1. 是.

  1. Yes.

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

Java interface default methods will help us in extending interfaces without having the fear of breaking implementation classes.

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

  1. AFAIK, static methods aren't needed to override, so being final of static methods is coherent. Overriding depends on having an instance of a class. A static method is not associated with any instance of a class so the concept is not applicable. However, default methods must have overrideable property as I quote above.

您可以在Java 8的界面中使用默认的ctor,私有字段,实例成员吗?


我喜欢使用默认方法,


I like to use thanks to default methods,

list.sort(ordering);

代替

Collections.sort(list, ordering);

这篇关于默认和静态方法如何在Java 8接口中工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 07:14