Introduction to Object-Oriented Programming

1. What is OOP

1.1 Definition

Object-Oriented Programming (OOP) is a programming paradigm based on objects and classes.

1.2 Procedural vs OOP

  • Procedural → focuses on functions
  • OOP → focuses on objects

1.3 Real-World Analogy

Think of a car:

  • Object → Car
  • Properties → color, speed
  • Methods → drive(), brake()

1.4 Objects and Classes

  • Class → blueprint
  • Object → instance of a class

1.5 Example

class Car {
    String color;    void drive() {
        System.out.println("Car is moving");
    }
}

2. Benefits of OOP

2.1 Code Reusability

Reuse code using inheritance.

2.2 Modularity

Break program into smaller parts (classes).

2.3 Maintainability

Easy to update and fix bugs.

2.4 Scalability

Programs can grow easily.

2.5 Security

Encapsulation hides data.

2.6 Real-World Modeling

Represents real-life objects effectively.


3. OOP Principles


3.1 Encapsulation

3.1.1 Definition

Wrapping data and methods into a single unit (class).

3.1.2 Data Hiding

Use private variables.

3.1.3 Example

class Student {
    private int marks;    public void setMarks(int m) {
        marks = m;
    }    public int getMarks() {
        return marks;
    }
}

3.1.4 Advantages

  • Protects data
  • Controls access

3.2 Inheritance

3.2.1 Definition

One class inherits properties of another.

3.2.2 Example

class Animal {
    void eat() {
        System.out.println("Eating");
    }
}class Dog extends Animal {
    void bark() {
        System.out.println("Barking");
    }
}

3.2.3 Advantages

  • Code reuse
  • Reduces duplication

3.3 Polymorphism

3.3.1 Definition

One method behaves differently in different situations.

3.3.2 Method Overloading

int add(int a, int b) {
    return a + b;
}double add(double a, double b) {
    return a + b;
}

3.3.3 Method Overriding

class Animal {
    void sound() {
        System.out.println("Animal sound");
    }
}class Dog extends Animal {
    void sound() {
        System.out.println("Dog barks");
    }
}

3.3.4 Advantages

  • Flexibility
  • Improves code design

3.4 Abstraction

3.4.1 Definition

Hiding implementation details and showing only functionality.

3.4.2 Abstract Class Example

abstract class Vehicle {
    abstract void start();
}

3.4.3 Interface Example

interface Animal {
    void sound();
}

3.4.4 Difference

  • Abstract class → can have methods with body
  • Interface → only method declarations (before Java 8 basics)

3.4.5 Advantages

  • Reduces complexity
  • Improves maintainability

Conclusion

Object-Oriented Programming is the core of Java development. By understanding concepts like encapsulation, inheritance, polymorphism, and abstraction, you can design clean, reusable, and scalable applications. These principles are widely used in real-world software development and form the foundation for advanced Java concepts.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *