What is the difference between abstract and interface in Java?
In Java, both abstract classes and interfaces are used to implement polymorphism, but they have some important distinctions.
- Definition: An abstract class is a special type of class that can contain both regular methods and abstract methods, and can have constructors. On the other hand, an interface is a pure abstract data type that can only contain abstract methods and constants, and cannot have constructors.
- Inheritance: A class can inherit only one abstract class, but can implement multiple interfaces.
- Implementation method: When a subclass inherits an abstract class, it must implement the abstract methods in it, otherwise the subclass must also be declared as an abstract class. When implementing an interface, the subclass must implement all the abstract methods in it.
- Abstract classes can have methods with different access modifiers, while methods in interfaces are by default public and cannot be changed.
- Variables: Abstract classes can have instance variables and static variables, while interfaces can only have constants.
- The purpose of using an abstract class is to share code and provide common methods, while the purpose of using an interface is to define a standard for classes to implement multiple behaviors.
In general, abstract classes are suitable for defining shared behavior within a class hierarchy, while interfaces are suitable for defining common behavior among multiple classes.