Object-Oriented Programming (OOP)
OOP is a programming style that uses objects (real-world entities) as the building blocks of
programs. A class defines the structure (blueprint), and an object is an instance of that class.
Main Concepts of OOP / Principles of OOP
Encapsulation
Binding data (variables) and methods (functions) together inside a class. Prevents direct
access to internal data, improving security.
Inheritance
A mechanism where one class can inherit the properties and methods of another class.
Promotes reusability.
Polymorphism
The ability of a method or object to take many forms. Example: the same method name but
different behaviors in different classes.
Abstraction
Hiding implementation details and showing only essential features to the user. Achieved
using abstract classes or interfaces in Java.
Example 1: Encapsulation (Car class in Java)
class Car {
// Encapsulation: private variables
private String brand;
private String color;
// Constructor
public Car(String brand, String color) {
this.brand = brand;
this.color = color;
}
// Method
public void drive() {
System.out.println(color + " " + brand + " is driving.");
}
}
public class Main {
public static void main(String[] args) {
Car car1 = new Car("Toyota", "Red");
Car car2 = new Car("Honda", "Blue");
car1.drive();
car2.drive();
}
}
Output:
Red Toyota is driving.
Blue Honda is driving.
Example 2: Inheritance + Polymorphism (Animal Example in Java)
class Animal {
public void sound() {
System.out.println("This animal makes a sound.");
}
}
class Dog extends Animal {
@Override
public void sound() {
System.out.println("Dog barks.");
}
}
class Cat extends Animal {
@Override
public void sound() {
System.out.println("Cat meows.");
}
}
public class Main2 {
public static void main(String[] args) {
Animal a1 = new Dog(); // Polymorphism
Animal a2 = new Cat();
a1.sound();
a2.sound();
}
}
Output:
Dog barks.
Cat meows.
Summary
- Encapsulation → Protects and bundles data.
- Inheritance → Reuses code from parent class.
- Polymorphism → One name, many forms (method overriding).
- Abstraction → Hides complexity, shows essentials.