Table of Contents
Introduction: class
Interfaces and abstract classes are both key concepts in object-oriented programming, but they serve slightly different purposes. We can say these are two different types of abstraction Object Oriented Programming Principle.
Abstraction:
It is a one of the Object Oriented Programming Principle. where implementation details are kept hidden from user and only highlighted set of services are visible to the user.
abstraction provides advantages like enhancement and security.
Types:
1. Interface
2. Abstract Class
- Abstract Class:
- An abstract class is a class that cannot be instantiated on its own; it’s meant to be subclassed.
- It can contain both abstract methods (methods without a body) and complete methods (methods with a body).
- Abstract methods define a contract that subclasses must follow by implementing those methods.
- Abstract classes can also have instance variables.
- Subclasses can extend only one abstract class, as Java does not support multiple inheritance for classes.
- Abstract classes can have constructors, which are invoked when a subclass is instantiated.
- They are used to represent abstract concepts or shared behavior among a group of related classes.
- Interface:
- An interface is like a contract; it defines a set of methods that a class implementing the interface must provide.
- Unlike abstract classes, interfaces cannot contain any implementation code. All methods declared in an interface are abstract by default.
- A class can implement multiple interfaces, providing flexibility in terms of defining behavior.
- Interfaces cannot have instance variables. They only define methods and constants.
- In Java, interfaces were used to achieve a form of multiple inheritance before the introduction of default methods in Java 8.
- Interfaces provide a way to achieve abstraction and ensure that different classes implementing the same interface adhere to a certain contract or behavior.
Conclusion:
In summary, abstract classes are used to provide a common structure and shared behavior among a group of related classes, while interfaces define a contract for behavior without any implementation. Both concepts play crucial roles in achieving abstraction, modularity, and polymorphism in object-oriented programming.