Main differences between Interfaces and Abstract classes
- Abstract class is an extensible program-code-template for creating objects, providing implementations of behavior (member functions or methods). On the other side interface is a contract between two interested parties.
- An interface contains only a signature of member (incomplete member) while an abstract class contains both abstract (incomplete) and complete member
- Methods and members of an abstract class can be defined with any visibility, whereas all methods of an interface must be defined as public (also they are defined public by default).
- Abstract classes can have constants, members, method stubs (methods without a body) and defined methods, whereas interfaces can only have constants and methods stubs.
- A child class can only extend a single class (abstract or concrete), whereas an interface can extend or a class can implement multiple other interfaces.
- A child class can define abstract methods with the same or less restrictive visibility, whereas a class implementing an interface must define the methods with the exact same visibility (public).
Abstract class establishes “is a” relation with concrete classes, while interface provides “has a” capability for classes.
At the end, when you should use interface or abstract class.
Consider using abstract classes if:
- You want to share code among several closely related classes.
- You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).
- You want to declare non-static or non-final fields. This enables you to define methods that can access and modify the state of the object to which they belong
Consider using interfaces if:
- You expect that unrelated classes would implement your interface. For example, many unrelated objects can implement the Serializable interface.
- You want to specify the behavior of a particular data type, but not concerned about who implements its behaviour.
- You want to take advantage of multiple inheritances of type.