Five important long question of oop
Five important long question of oop
- **Encapsulation**: The concept of wrapping data (variables) and the methods (functions) that
operate on the data into a single unit called a class.
- **Abstraction**: Hiding the complex implementation details and showing only the essential
features of the object.
- **Inheritance**: The ability to create a new class (derived class) from an existing class (base
class), inheriting attributes and methods.
- **Polymorphism**: The ability of a single function, method, or operator to work in different ways
based on the objects involved.
---
---
---
---
```python
# Parent class
class Animal:
def __init__(self, name, age):
self.name = name # Encapsulation: Attribute (name) is encapsulated
self.age = age # Encapsulation: Attribute (age) is encapsulated
# Child class 1
class Dog(Animal):
def __init__(self, name, age, breed):
super().__init__(name, age) # Inheritance: Inheriting from Animal class
self.breed = breed
# Child class 2
class Cat(Animal):
def __init__(self, name, age, color):
super().__init__(name, age) # Inheritance: Inheriting from Animal class
self.color = color
```
- **Encapsulation**: The attributes `name` and `age` in the `Animal` class are encapsulated,
meaning they are contained within the class and can be accessed or modified only via methods.
- **Inheritance**: The `Dog` and `Cat` classes inherit from the `Animal` class, allowing them to
reuse the attributes (`name`, `age`) and methods of the `Animal` class.
- **Polymorphism**: Both `Dog` and `Cat` classes override the `speak()` method of the parent
`Animal` class. When `speak()` is called on instances of these classes, they behave differently,
displaying "Woof!" and "Meow!", respectively.
---