When to Use Abstract Class and Interface
How do we know when to use interface or abstract class?
Interface
Interface declares a set a methods of an object, a class need to implement the methods define in the interface, and it can implement multiple interface.
- any field defined in the interface is
public static final
- no static method
- starts from JDK 8, an interface can have default method
- an interface also may not include any method just a marker
Interface forms a contract between the class and the outside world, and this contract is enforced at build time by the compiler.
Consider using interfaces if any of these statements apply to your situation:
- You expect that unrelated classes would implement your interface. For example, the interfaces Comparable and Cloneable are implemented by many unrelated classes.
- You want to specify the behavior of a particular data type, but not concerned about who implements its behavior.
- You want to take advantage of multiple inheritances.
Abstract Class
An abstract class is a class that is declared as abstract, and can have common fields, methods defined like a template,
- it may or may not include abstract methods
- can not be instantiated
- no multiple inheritance
- it may or may not include methods, static methods
Consider use abstract class if any of these statements apply to your situation"
- 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
- You expect that classes that extend your abstract class have many common methods or fields other that public (such as protected and private)
- You want to share code among several closely related classes