Question

I have the following interface in Java

public interface IFoo
{
    public abstract void foo();
    public void bar();
}

What is the difference between foo() and bar()? When should I use abstract?

Both seem to accomplish what I want unless I'm missing something subtle?

Update Duplicate of Why would one declare a Java interface method as abstract?

Was it helpful?

Solution

There isn't any functional difference. No implementation is ever provided in a java interface so all method declarations are implicitly abstract.

See [1]: http://java.sun.com/docs/books/tutorial/java/IandI/abstract.html

A direct quote form the above:

Note: All of the methods in an interface (see the Interfaces section) are implicitly abstract, so the abstract modifier is not used with interface methods (it could be—it's just not necessary).

OTHER TIPS

Interface methods are both public and abstract by default. There's no difference between foo() and bar() and you can safely remove all public and abstract keywords.

You're not missing anything. From the Java Language Specification:

Every method declaration in the body of an interface is implicitly abstract, so its body is always represented by a semicolon, not a block.

Every method declaration in the body of an interface is implicitly public.

In other words, you can omit the public as well as the abstract on the interface methods.

It's redundant (there's no difference between the two declarations) and explicitly discouraged in section 9.4 of the Java Language specification:

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.

And public is similarly unnecessary and discouraged:

It is permitted, but strongly discouraged as a matter of style, to redundantly specify the public modifier for interface methods.

I don't know why public is strongly discouraged but abstract is just discouraged...

Both accomplish the same, since all methods in an interface are abstract.

abstract in this scenario is unnecessary (as is marking methods in interfaces as public).

You would instead use this on a method in an abstract class in order to enforce its overriding by a subclass.

There no are difference between declarations. Conceptually, all methods in an interface are abstract.

It makes no difference. All the methods in a java interface are always abstract.

See the first note at this link : http://java.sun.com/docs/books/tutorial/java/IandI/abstract.html

Both foo() and bar() are abstract as they are declared inside an interface. The abstract word you used here is of no significance - you better remove it.

Interfaces in java are equal "somehow" to a fully abstract classes, so adding the "abstract" keyword to a method declaration in an interface has nothing to do with the method!

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top