eli
eli

Reputation: 335

Why doesn't the static method in an interface not need a default access modifier?

public interface Drive {
   int getNumWheels();

   default int driveMiles(){
      return 10;
   }

   static int getColorID(){
     return 0;
   }
}

In the code above, why doesn't the static method in an interface not need a default access modifier? I understand that the default method was added in JDK 8, and provides an optional implementation, however, I am a little unclear about the static method? This seems really similar to a class's static method?

Upvotes: 0

Views: 85

Answers (2)

Ravindra babu
Ravindra babu

Reputation: 38910

There is a difference in purpose of default and static methods.

When you extend an interface that contains a default method, you can do the following:

  1. Not mention the default method at all, which lets your extended interface inherit the default method.
  2. Redeclare the default method, which makes it abstract.

  3. Redefine the default method, which overrides it.

Static Methods

A static method is a method that is associated with the class in which it is defined rather than with any object. Every instance of the class shares its static methods.

If you are redefining static method in another class, you are hiding the definition in first interface.

Refer to oracle documentation page about default and static methods.

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533492

In the code above, why doesn't the static method in an interface not need a default access modifier?

I guess you are asking, why is it static and not static default?

In classes you can just use static and most likely they thought it would be simpler to keep it consistent.

This seems really similar to a class's static method?

Which is why I believe the syntax is the same.


A better question would be

why do we use default as a modifier at all?

There is two reasons I can think of

  • default is already a keyword so easy to reuse in the language and it is used in a similar way in annotations.
  • it makes it clear that this method is intended to have an implementation. They could have dropped the need for a keyword at all, but a little redundancy can improve code quality.

why did they decide to include static in an interface for JDK 8?

The benefit is the same as for a class. You can define a method which is associated with an interface but is not tied to a particular class. A good example is factory classes. In the past you would have to have say

Logger LOGGER = LoggerFactory.getLogger(...);

If you wanted Logger to be an interface, it's factory method, which must be static had to use a utility class. Now your API could be

Logger LOGGER = Logger.get(...);

The interface for the factory method is the same as the interface it returns so there is less reason to quality exactly what type get returns.

Upvotes: 2

Related Questions