Difference between abstract class and interface
Here are the key differences between an abstract class and an interface in Java:
Implementation: An abstract class can have both abstract and non-abstract methods, whereas an interface can only have abstract methods (implicitly abstract) and constants. Abstract classes can provide default implementations for some or all of their methods, while interfaces cannot provide any method implementations.
Inheritance: A class can only extend one abstract class, but it can implement multiple interfaces. This is because Java supports single inheritance for classes but multiple inheritance for interfaces. So, if a class needs to inherit behavior from multiple sources, interfaces are used.
Instantiation: An abstract class cannot be instantiated directly with the "new" keyword. It serves as a base for subclasses to inherit from. On the other hand, an interface cannot be instantiated at all. It defines a contract that implementing classes must adhere to.
Access Modifiers: Abstract classes can have different access modifiers (public, protected, private) for their members, while interfaces only allow public access for methods and constants.
Fields and Constants: Abstract classes can have fields (member variables) with any access modifier, while interfaces can only have constants (static final variables).
Usage: Abstract classes are generally used when you want to provide a common base implementation and share code among related classes. Interfaces, on the other hand, are used when you want to define a contract that multiple unrelated classes can implement to provide their own behavior.
In summary, abstract classes are used to define common characteristics and provide default behavior for subclasses, while interfaces define contracts that unrelated classes can adhere to, allowing for polymorphism and multiple inheritance of behavior. Abstract classes focus on the "is-a" relationship, while interfaces focus on the "can-do" relationship.