pokuri
pokuri

Reputation: 156

java8 Interface allowing public default method

In java 8 default method implementation can take both public and default modifier. 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;
}

Upvotes: 3

Views: 1079

Answers (2)

Lefteris008
Lefteris008

Reputation: 906

As the others suggested, the default keyword has two main uses:

  • Prior to Java 8, it can only be employed to trigger the default case in a switch-case statement.
  • 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()).

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.

For an extensive discussion on the purpose of default methods in interfaces, see Purpose of Default or Defender methods in Java 8

Upvotes: 3

Jon Skeet
Jon Skeet

Reputation: 1503120

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.

From JLS 9.4:

Every method declaration in the body of an interface is implicitly public (§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.

Upvotes: 9

Related Questions