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?
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.
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.
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.
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.
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).
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With