Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would one declare a Java interface method as abstract?

People also ask

Why interface methods are abstract?

An interface is like a "purely" abstract class. The class and all of its methods are abstract. An abstract class can have implemented methods but the class itself cannot be instantiated (useful for inheritance and following DRY).

Why we declare method as abstract in Java?

In object oriented programming, abstraction is defined as hiding the unnecessary details (implementation) from the user and to focus on essential details (functionality). It increases the efficiency and thus reduces complexity.

What is the use of abstract method in interface in Java?

The interface in Java is a mechanism to achieve abstraction. There can be only abstract methods in the Java interface, not method body. It is used to achieve abstraction and multiple inheritance in Java. In other words, you can say that interfaces can have abstract methods and variables.

Can an interface be declared as abstract?

The interface body can contain abstract methods, default methods, and static methods. An abstract method within an interface is followed by a semicolon, but no braces (an abstract method does not contain an implementation).


According to the Java Language Specification, the abstract keyword for interfaces is obsolete and should no longer be used. (Section 9.1.1.1)

That said, with Java's propensity for backwards compatibility, I really doubt it will ever make a difference whether the abstract keyword is present.


"The benefice of that" (adding abstract on interface methods declaration) in eclipse would be an old compatibility issue with jdt eclipse compiler in jdk1.3

Since 1.4, jdk libraries are no longer containing default abstract methods (on abstract classes implementing interfaces).
This is fooling the Eclipse 1.3 compiler diagnosis since their implementation is relying on their existence.
Note that Javac 1.3 would refuse altogether to perform against 1.4 libraries (using -bootclasspath option).

Since the Eclipse compiler is likely to be in 1.4 compliance level (see Workbench>Preferences>Java>Compiler>JDK Compliance), or use at least 1.3 class libraries if using 1.3 compliance mode, the presence of "abstract" is not required in most of the current eclipse projects.


From the Java SE 7 JLS (Java Language Specification): "It is permitted, but discouraged as a matter of style, to redundantly specify the public and/or abstract modifier for a method declared in an interface."

For Java SE 5.0: "For compatibility with older versions of the Java platform, it is permitted but discouraged, as a matter of style, to redundantly specify the abstract modifier for methods declared in interfaces."


According to JLS methods in interfaces are abstract by default, so the keyword is redundant. Knowing this, I'd never use it to "avoid presentational clutter".