Object-Oriented Programming (OOP)

-> Java is an Object-Oriented Programming (OOP) language based on objects.

-> OOP promotes modularity, reusability, and scalability.

1. Classes & Objects

A class is a blueprint for creating objects. An object is an instance of a class.

class Car {  
    String brand;  
    int speed;  

    void accelerate() {  
        speed += 10;  
        System.out.println(brand + " is running at " + speed + " km/h.");  
    }  
}

public class Main {  
    public static void main(String[] args) {  
        Car myCar = new Car();  
        myCar.brand = "Toyota";  
        myCar.speed = 50;  
        myCar.accelerate();  
    }  
}
            

2. Encapsulation

Encapsulation means hiding data inside a class and controlling access via getters and setters.

class BankAccount { 
    private double balance;  

    public void deposit(double amount) {  
        if (amount > 0) balance += amount;  
    }  

    public double getBalance() {  
        return balance;  
    }  
}
            

3. Inheritance

Inheritance allows one class to inherit properties and methods from another.

class Animal {  
    void makeSound() {  
        System.out.println("Some sound...");  
    }  
}

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

public class Main {  
    public static void main(String[] args) {  
        Dog myDog = new Dog();  
        myDog.makeSound();  
        myDog.bark();  
    }  
}
            

4. Polymorphism

Polymorphism allows methods to have multiple implementations, such as method overriding.

class Animal {  
    void makeSound() {  
        System.out.println("Animal makes a sound");  
    }  
}

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

5. Abstraction

Abstraction hides implementation details and exposes only the essential features.

abstract class Vehicle {  
    abstract void start();  
}

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

6. Interfaces

An interface only contains abstract methods.

interface Animal {  
    void makeSound();  
}

class Cat implements Animal {  
    public void makeSound() {  
        System.out.println("Meow");  
    }  
}
            

Attempt Test oops concept