Lesson

Introduction

Opps/Java

Java OOP (Object-Oriented Programming) Introduction


What is OOP?

  • OOP = Object-Oriented Programming

  • A programming approach based on classes and objects

  • Used to model real-world entities

Class

  • A blueprint/template to create objects

  • Contains:

    • Variables (data)

    • Methods (functions)

plaintext
class Car {
    String color;
    int speed;

    void drive() {
        System.out.println("Car is running");
    }
}

Object

  • An instance of a class

  • Used to access class properties and methods

plaintext
Car c1 = new Car();
c1.color = "Red";
c1.drive();

Pillars of OOP


1. Encapsulation šŸ”’

  • Wrapping data + methods into a single unit

  • Use private variables + getters/setters

  • Data hiding

  • Secure code

java
class Student {
    private int marks;

    public void setMarks(int m) {
        marks = m;
    }

    public int getMarks() {
        return marks;
    }
}

2. Inheritance

  • One class inherits another class

  • Use extends keyword

  • Code reuse

  • Parent → Child relationship

java
class Animal {
    void eat() {
        System.out.println("Eating");
    }
}

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

3. Polymorphism

  • One method, multiple forms

Types:

  • Method Overloading (compile-time)

  • Method Overriding (runtime)

java
class MathUtil {
    int add(int a, int b) {
        return a + b;
    }

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

4. Abstraction

  • Hiding implementation details

  • Show only important features

Key Points:

  • Use abstract class or interface

  • Reduce complexity

java
abstract class Vehicle {
    abstract void start();
}

class Car extends Vehicle {
    void start() {
        System.out.println("Start with key");
    }
}

Advantages of OOP

  • āœ” Code reusability

  • āœ” Easy maintenance

  • āœ” Data security

  • āœ” Real-world modeling


Quick Short

  • Class → Blueprint

  • Object → Instance

  • Encapsulation → Data hiding

  • Inheritance → Code reuse

  • Polymorphism → Many forms

  • Abstraction → Hide details