The Difference between Abstract Class and Interface is as follows:
| Topic | Abstract Class | Interface |
|---|---|---|
| Method Type | Abstract class can have abstract and non-abstract methods. | Interface could have only abstract methods upto java 7, but later from java 8 it can also have default and static methods. |
| Variables Type | Abstract class can have final, non-final, static and non-static variables. | Interface has only static and final variables. |
| Final Variables | An abstract class may contain non-final variables. | Variables declared in a Java interface are by default final. |
| Inheritance/Abstraction | abstract class can be extended using keyword “extends”. | A Java interface can be implemented using keyword “implements”. |
| Multiple implementation | an abstract class can extend another Java class and implement multiple Java interfaces. | An interface can extend another Java interface only. |
| Accessibility of Data members | An abstract class can have class members like private, protected, etc. | Members of a Java interface are public by default. |
| Limit of Extensions | It can extend only one class or one abstract class at a time. | It can extend any number of interfaces. |
| Constructor or destructors | An abstract class can declare constructors and destructors. | An interface cannot declare constructors or destructors. |
| Example | public abstract class Shape{
public abstract void draw();
} | public interface Drawable{
void draw();
} |
Most Important Question : When to use what?
Use Abstract Class when :
- There is some part of functionality which seems to be common for other related classes, then you can put these lines of code within abstract class and this abstract class should be extended by all these related classes.
- Abstract class allows code reusability.
Use Interface when :
- You need total abstraction, All methods declared within an interface must be implemented by the class(es) that implements this interface.
- Allows you to separate the definition of a method from the inheritance hierarchy.
Summary
In this article we learnt about the difference between Abstract Class and Interface in java.
Hope you liked the article !