OOP Introduction Notes Detailed
OOP Introduction Notes Detailed
1. Encapsulation:
Encapsulation is the bundling of data (attributes) and methods
(functions) that operate on the data into a single unit, called a class. It
ensures that the internal details of the object are hidden from the
outside world and can only be accessed through predefined methods.
Example:
class BankAccount {
private double balance;
Output:
Balance: 1000.0
2. Abstraction:
Abstraction hides unnecessary implementation details from the user
and only exposes the essential features. It allows developers to work
with higher-level concepts instead of worrying about the internal
workings.
Example:
abstract class Shape {
abstract void draw();
}
Output:
Drawing a Circle
3. Inheritance:
Inheritance allows a child class to inherit the properties and methods
of a parent class. This promotes code reuse and establishes a
parent-child relationship.
Example:
class Animal {
void eat() {
System.out.println("This animal eats food");
}
}
Output:
This animal eats food
This dog barks
4. Polymorphism:
Polymorphism allows an object to take many forms. It is commonly
implemented through method overloading (same method name with
different parameters) and overriding (child class redefines a method
of the parent class).
Example of Overloading:
class Calculator {
int add(int a, int b) {
return a + b;
}
Example of Overriding:
class Animal {
void sound() {
System.out.println("This animal makes a sound");
}
}
class Cat extends Animal {
@Override
void sound() {
System.out.println("Meow");
}
}
Output:
Meow
Example:
class Car {
String brand;
int speed;
void drive() {
System.out.println(brand + " is driving at " + speed + " km/h");
}
}
Output:
Toyota is driving at 120 km/h
Advantages of OOP:
1. Modularity: Code is divided into classes, making it easier to debug
and maintain.
2. Reusability: Inheritance and polymorphism enable code reuse.
3. Scalability: New features can be added easily by extending classes.
4. Security: Encapsulation protects sensitive data from external
access.
Conclusion:
OOP provides a powerful way to model real-world systems in
software. By using concepts like encapsulation, inheritance,
polymorphism, and abstraction, developers can build scalable and
maintainable applications. It has become a cornerstone of modern
programming and is widely used in languages like Java, Python, C++,
and Ruby.