Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Java, when should I use an abstract method in an interface?

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?

like image 337
John Oxley Avatar asked Sep 29 '09 12:09

John Oxley


People also ask

Is it necessary to have abstract method in interface?

Because by default all methods are abstract inside the interface. So this example states that we can not have final methods inside the interfaces. Hence, this example also shows that we can have abstract methods only inside the interface.

When should I go with abstract class and when should I use interface?

The short answer: An abstract class allows you to create functionality that subclasses can implement or override. An interface only allows you to define functionality, not implement it. And whereas a class can extend only one abstract class, it can take advantage of multiple interfaces.

When should abstract methods be used?

If both the Java interface and Java abstract class are used to achieve abstraction, when should an interface and abstract class be used? An abstract class is used when the user needs to define a template for a group of subclasses. An interface is used when a user needs to define a role for other classes.

When should we use abstract class and interface in Java?

If you are creating something that provides common functionality to unrelated classes, use an interface. 2. If you are creating something for objects that are closely related in a hierarchy, use an abstract class.


2 Answers

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).

like image 187
Alex Stoddard Avatar answered Sep 30 '22 19:09

Alex Stoddard


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.

like image 20
Martin Blech Avatar answered Sep 30 '22 18:09

Martin Blech