Your Page Title
🔍

    Object-Oriented Programming (OOP)

    Let’s start from the beginning of Object-Oriented Programming (OOP) in Java, including examples of code to help illustrate the concepts. We’ll cover the core concepts like objects, classes, inheritance, encapsulation, polymorphism, and abstraction using code examples for clarity.

    What is Object-Oriented Programming (OOP)?

    OOP is a programming model where software design revolves around objects that represent real-world entities. Each object contains attributes (data) and methods (functions) that define its behavior. Instead of just focusing on procedures or functions, OOP models things based on objects and how they interact.

    Example of an Object:

    Consider a Car object in a real-world system:

    • Attributes (data): Color, model, speed, year of manufacture.
    • Methods (behavior): Start, stop, accelerate, brake.

    In Java, we can model this as follows:

    Example: Creating a Class and Objects

    javaCopy code// Define a class (blueprint) for Car
    class Car {
        // Attributes of the car (fields)
        String color;
        String model;
        int year;
        int speed;
    
        // Constructor to initialize the car
        Car(String color, String model, int year, int speed) {
            this.color = color;
            this.model = model;
            this.year = year;
            this.speed = speed;
        }
    
        // Methods of the car (behavior)
        void start() {
            System.out.println(model + " has started.");
        }
    
        void accelerate(int increaseSpeed) {
            speed += increaseSpeed;
            System.out.println(model + " is accelerating. Speed is now: " + speed);
        }
    
        void stop() {
            System.out.println(model + " has stopped.");
            speed = 0;
        }
    }
    
    public class Main {
        public static void main(String[] args) {
            // Create an object of the Car class
            Car myCar = new Car("Red", "Toyota", 2022, 0);
    
            // Using the methods of the Car object
            myCar.start();
            myCar.accelerate(50);  // Accelerate by 50 units
            myCar.stop();
        }
    }
    

    Explanation:

    • Class: Car is a blueprint or template that defines what a car is (its attributes) and what it can do (its methods).
    • Object: myCar is an instance of the Car class with specific values for its attributes (red, Toyota, 2022).
    • Constructor: Car() initializes the object with data like color, model, year, and speed.
    • Methods: start(), accelerate(), and stop() define the behaviors or actions that a car can perform.

    Core Concepts of OOP

    1. Encapsulation:

    Encapsulation is about bundling the data (attributes) and methods (behaviors) together into a single unit (the object). It also controls the access to this data through access modifiers like private, protected, or public.

    javaCopy codeclass Car {
        // Encapsulation: Fields are private to protect the data
        private String color;
        private String model;
        private int year;
        private int speed;
    
        // Public getter and setter methods to access private fields
        public String getColor() {
            return color;
        }
    
        public void setColor(String color) {
            this.color = color;
        }
    
        public void start() {
            System.out.println(model + " has started.");
        }
    }
    

    Here, we encapsulate the data by declaring it private and only allow controlled access through public methods (getters and setters). This helps protect the internal state of the object.

    2. Inheritance:

    Inheritance allows one class to inherit the attributes and methods from another class. It helps in code reuse.

    javaCopy code// Base class (Parent)
    class Vehicle {
        int speed;
    
        void stop() {
            System.out.println("The vehicle has stopped.");
        }
    }
    
    // Derived class (Child) inherits from Vehicle
    class Car extends Vehicle {
        String model;
    
        // Additional method in Car
        void start() {
            System.out.println(model + " has started.");
        }
    }
    
    public class Main {
        public static void main(String[] args) {
            // Create a Car object which inherits from Vehicle
            Car myCar = new Car();
            myCar.model = "Honda";
            myCar.start();     // Calls start() from Car
            myCar.stop();      // Calls stop() from Vehicle (inherited method)
        }
    }
    
    • Inheritance: The Car class inherits from the Vehicle class, reusing its stop() method and adding its own start() method.

    3. Polymorphism:

    Polymorphism allows methods to behave differently based on the object calling them. There are two types:

    • Method Overloading: Same method name with different parameters.
    • Method Overriding: A method in the child class overrides the method in the parent class.
    javaCopy code// Base class
    class Vehicle {
        void start() {
            System.out.println("Vehicle is starting.");
        }
    }
    
    // Derived class overrides the start() method
    class Car extends Vehicle {
        @Override
        void start() {
            System.out.println("Car is starting.");
        }
    }
    
    public class Main {
        public static void main(String[] args) {
            Vehicle myVehicle = new Vehicle();
            Car myCar = new Car();
    
            // Calls the start() method of Vehicle
            myVehicle.start();  // Output: Vehicle is starting.
    
            // Calls the overridden start() method of Car
            myCar.start();      // Output: Car is starting.
        }
    }
    
    • Overriding: The Car class overrides the start() method from the Vehicle class. Based on the object type, the correct method is called.

    4. Abstraction:

    Abstraction hides complex details and shows only the essential features. It can be implemented using abstract classes or interfaces.

    javaCopy code// Abstract class
    abstract class Vehicle {
        // Abstract method (no body)
        abstract void start();
    
        // Regular method
        void stop() {
            System.out.println("Vehicle stopped.");
        }
    }
    
    // Derived class implementing the abstract method
    class Car extends Vehicle {
        @Override
        void start() {
            System.out.println("Car is starting.");
        }
    }
    
    public class Main {
        public static void main(String[] args) {
            Vehicle myCar = new Car();  // Create an object of the derived class
            myCar.start();   // Calls the Car's start() method
            myCar.stop();    // Calls the stop() method from Vehicle class
        }
    }
    
    • Abstract Class: Vehicle has an abstract method start() that is implemented by the Car class. This ensures that every subclass of Vehicle will provide its own version of start().

    OOP Advantages:

    1. Code Reusability: With inheritance, classes can reuse code, reducing duplication.
    2. Data Security: Encapsulation protects the object’s data from unintended modifications.
    3. Flexibility: Polymorphism allows the same code to work with different object types, making programs flexible and extensible.
    4. Abstraction: Hides complexity and allows focusing on the relevant details of a problem.

    Summary:

    • OOP helps organize complex software by modeling real-world entities as objects with attributes (data) and methods (behavior).
    • Encapsulation protects the internal state, inheritance promotes code reuse, polymorphism allows flexibility, and abstraction hides complexity.