简体   繁体   English

java8接口允许公共默认方法

[英]java8 Interface allowing public default method

In java 8 default method implementation can take both public and default modifier. 在java 8中,默认方法实现可以同时使用publicdefault修饰符。 What is the main difference between below two methods. 以下两种方法的主要区别是什么? Under which conditions which type need to follow. 在哪种条件下需要遵循哪种类型。

default int makeMul(int x, int y) {
    return x * y;
}

public default int makeMul(int x, int y) {
    return x * y;
}

There's nothing special about default methods here. 这里的默认方法没什么特别之处。 Java has always allowed interface methods to be declared public, even though they're already implicitly public. Java一直允许将接口方法声明为public,即使它们已经隐式公开。

From JLS 9.4 : 来自JLS 9.4

Every method declaration in the body of an interface is implicitly public (§6.6). 接口主体中的每个方法声明都是隐式公共的(第6.6节)。 It is permitted, but discouraged as a matter of style, to redundantly specify the public modifier for a method declaration in an interface. 允许但不鼓励作为样式,在接口中冗余地指定方法声明的公共修饰符。

As the others suggested, the default keyword has two main uses: 正如其他人所建议的那样, default关键字有两个主要用途:

  • Prior to Java 8, it can only be employed to trigger the default case in a switch-case statement. 在Java 8之前,它只能用于在switch-case语句中触发默认情况。
  • From Java 8 onwards, developers are allowed to provide implemented methods inside interfaces (which previously wasn't possible), with the use of the default keyword at the method's declaration ( public default int method() ). 从Java 8开始,允许开发人员在接口内部提供实现的方法(之前是不可能的),在方法的声明中使用default关键字( public default int method() )。

As far as I understand, using the default keyword at a method's declaration when in a simple class , does not make any difference at all. 据我所知,在一个简单的类中 ,在方法声明中使用default关键字,根本没有任何区别。

For an extensive discussion on the purpose of default methods in interfaces, see Purpose of Default or Defender methods in Java 8 有关接口中default方法的目的的广泛讨论,请参阅Java 8中的Default或Defender方法的目的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM