What are 4 types of OOPS?
In Object-Oriented Programming (OOP), there are four fundamental concepts that form the foundation of the paradigm. These concepts are:
1. Encapsulation
Encapsulation is the concept of bundling data (attributes) and methods (functions) that operate on the data into a single unit, known as a class. It restricts direct access to some of the object's components, which helps to protect the integrity of the data.
- Example: In a class representing a bank account, the balance would be a private member, and the class would provide public methods to deposit or withdraw money, ensuring that the balance cannot be modified directly.
2. Inheritance
Inheritance allows a new class (derived class) to inherit properties and behaviors from an existing class (base class). This promotes code reusability and establishes a hierarchical relationship between classes.
- Example: A class
Animal
could be a base class, while classesDog
andCat
could be derived classes that inherit common attributes and methods fromAnimal
.
3. Polymorphism
Polymorphism enables objects of different classes to be treated as objects of a common base class. It allows methods to be invoked on objects of derived classes through base class references or pointers, enabling dynamic method resolution.
- Example: If both
Dog
andCat
classes have a methodspeak()
, a base class pointer can callspeak()
on an object of either derived class, executing the appropriate method based on the actual object type.
4. Abstraction
Abstraction involves hiding the complex implementation details and exposing only the necessary features of an object. It allows focusing on what an object does instead of how it does it, often achieved using abstract classes and interfaces.
- Example: A class
Shape
might define an abstract methoddraw()
, while derived classes likeCircle
andSquare
provide specific implementations of how to draw those shapes.
Conclusion
These four concepts—encapsulation, inheritance, polymorphism, and abstraction—are integral to OOP, allowing for better data management, code organization, and software development practices.
Sources
GET YOUR FREE
Coding Questions Catalog