tryingToLearn
tryingToLearn

Reputation: 11653

JAVA: Can interface have non abstarct methods?

I was browsing through Oracle docs, when i came across this:

https://docs.oracle.com/javase/tutorial/java/IandI/override.html

From what I knew, Interfaces in JAVA can have only abstract methods, but after reading this article I realized I was wrong. Can someone explain me the implications of using non abstract methods in Interfaces?

EDIT: In JAVA 1.6 , follwoing gives error:

public interface NonAbstractMethods {

    void testNonAbstract(){

    }
}

Error Message: Abstract methods do not specify a body

Upvotes: 1

Views: 1076

Answers (4)

Vikas Kumar
Vikas Kumar

Reputation: 1

Methods in interface are public and abstract by default. Abstract methods don't have an implementation. Only static methods with implementation are allowed in interface all other methods should be public and abstract by default.Method u wrote is not abstract as it is having implementation and neither is it static so it is showing Abstract method don't specify a body error.

Note: A static method in interface must have implementation.

public interface NonAbstractMethods {
   static void testNonAbstract(){
}
}

This code will not show error.

Upvotes: -2

Neo
Neo

Reputation: 304

The interface method specified in the example is a default interface method, a feature introduced in Java 8. A default method allows the developer to add new methods to an interface without breaking the existing implementation of the interface. Read more here, https://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html

Upvotes: 1

Valentin Cavel
Valentin Cavel

Reputation: 228

Java 8 introduced the concept of default methods in interfaces. This would be the closest I know from what you are describing.

Here is the doc for default methods : https://docs.oracle.com/javase/tutorial/java/IandI/defaultmethods.html

It is basically a default behavior for the classes inheriting the interface.

Edit : As gerrytan pointed out, it also allows you to add methods in your interface without breaking the classes that already implement it.

Upvotes: 3

gerrytan
gerrytan

Reputation: 41133

Default methods in interface are only introduced in java 8. Basically it gives you default implementation if the implementing class did not override it.

This also adds the benefit where if you refactor the interface and introduced a new method, it won't break existing implementing classes.

Upvotes: 6

Related Questions