Understanding OOPs Concepts in Java: A Comprehensive Guide

Everything You Need to Know About OOP in Java: A Beginner's Guide

In this blog, we will discuss the various OOP concepts in Java in detail.

  1. Classes and Objects In Java, everything is an object. A class is a blueprint for creating objects. It defines the properties and behaviors of an object. An object is an instance of a class. For example, consider a class called "Person" that defines the properties and behaviors of a person. A person object can be created from this class, which represents an actual person with specific attributes and behaviors.

here is a simple example that can help you understand Classes and Objects in Java:

Consider a class called "Car". This class can be used to define the properties and behaviors of a car. Here's what the class would look like:

public class Car {
    String make;
    String model;
    int year;
    String color;

    void start() {
        System.out.println("The " + make + " " + model + " has started.");
    }

    void stop() {
        System.out.println("The " + make + " " + model + " has stopped.");
    }
}

In this class, we have defined four properties: make, model, year, and color. We have also defined two methods: start() and stop(). The start() method prints a message indicating that the car has started, and the stop() method prints a message indicating that the car has stopped.

Now, we can create an object of this class and set its properties as follows:

Car myCar = new Car();
myCar.make = "TATA";
myCar.model = "Punch";
myCar.year = 2023;
myCar.color = "Silver";

In this code, we have created an object of the Car class called "myCar". We have set its properties to specify that it is a 2023 TATA Punch in silver color.

We can now call the methods of the myCar object to start and stop the car as follows:

myCar.start();
myCar.stop();

When we run this code, we get the following output:

The TATA Punch has started.
The TATA Punch has stopped.
  1. Encapsulation is the process of hiding the implementation details of an object from the outside world. It is achieved through access modifiers such as public, private, and protected. By hiding the implementation details, encapsulation ensures that the object's data and methods are accessed only through a well-defined public interface. This helps in maintaining the integrity of data by preventing unauthorized access.

let's continue with the "Car" class example to explain Encapsulation in Java:

In the "Car" class example, we can encapsulate the properties by making them private and providing public methods to access them. Here's what the modified "Car" class would look like:

public class Car {
    private String make;
    private String model;
    private int year;
    private String color;

    public void setMake(String make) {
        this.make = make;
    }

    public String getMake() {
        return make;
    }

    public void setModel(String model) {
        this.model = model;
    }

    public String getModel() {
        return model;
    }

    public void setYear(int year) {
        this.year = year;
    }

    public int getYear() {
        return year;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public String getColor() {
        return color;
    }

    public void start() {
        System.out.println("The " + make + " " + model + " has started.");
    }
    public void stop() {
        System.out.println("The " + make + " " + model + " has stopped.");
    }
}

In this modified "Car" class, we have made the properties "make", "model", "year", and "color" private. We have also provided public getter and setter methods to access and modify these properties. The methods "start()" and "stop()" are still public and can be accessed from outside the class.

Now, we can create an object of this class and set its properties using the setter methods as follows:

Car myCar = new Car();
myCar.setMake("TATA");
myCar.setModel("Punch");
myCar.setYear(2023);
myCar.setColor("Silver");

In this code, we have created an object of the Car class called "myCar" and set its properties using the setter methods.

We can now call the methods of the myCar object to start and stop the car as follows:

myCar.start();
myCar.stop();

When we run this code, we get the following output:

The TATA Punch has started.
The TATA Punch has stopped.

This example demonstrates how encapsulation can be used to hide the internal details of an object and provide a public interface to access it. By making the properties private and providing public getter and setter methods, we can control the access to the object's data and methods and ensure that they are accessed in a controlled manner.

  1. Inheritance is a mechanism that allows a new class to be based on an existing class. The new class inherits the properties and methods of the existing class, and can also add new properties and methods of its own. Inheritance is used to create a hierarchy of classes that share common properties and behaviors. For example, consider a class called "Animal". This class can be used as a base class for other classes such as "Dog" and "Cat" that share common properties and behaviors of an animal.

let's continue with the "Car" class example to explain Inheritance in Java:

In our "Car" class example, we can create a new class called "ElectricCar" that inherits from the "Car" class and has some additional properties and methods that are specific to electric cars. Here's what the "ElectricCar" class would look like:

public class ElectricCar extends Car {
    private int batteryCapacity;
    private int maxRange;

    public void setBatteryCapacity(int batteryCapacity) {
        this.batteryCapacity = batteryCapacity;
    }

    public int getBatteryCapacity() {
        return batteryCapacity;
    }

    public void setMaxRange(int maxRange) {
        this.maxRange = maxRange;
    }

    public int getMaxRange() {
        return maxRange;
    }

    public void charge() {
        System.out.println("The electric car is charging.");
    }
}

In this "ElectricCar" class, we have extended the "Car" class using the "extends" keyword, which means that the "ElectricCar" class now inherits all the properties and methods of the "Car" class. We have also added two new properties, "batteryCapacity" and "maxRange", and a new method called "charge()".

We can now create an object of the "ElectricCar" class and set its properties as follows:

ElectricCar myElectricCar = new ElectricCar();
myElectricCar.setMake("Tesla");
myElectricCar.setModel("Model S");
myElectricCar.setYear(2022);
myElectricCar.setColor("Red");
myElectricCar.setBatteryCapacity(100);
myElectricCar.setMaxRange(400);

In this code, we have created an object of the "ElectricCar" class called "myElectricCar" and set its properties using the setter methods. Since "ElectricCar" inherits from "Car", we can also call the "start()" and "stop()" methods of the "Car" class on the "myElectricCar" object:

myElectricCar.start();
myElectricCar.stop();

We can also call the "charge()" method that is specific to the "ElectricCar" class:

myElectricCar.charge();

When we run this code, we get the following output:

The Tesla Model S has started.
The Tesla Model S has stopped.
The electric car is charging.

This example demonstrates how Inheritance can be used to create a new class that extends an existing class and adds new properties and methods. By inheriting from the "Car" class, the "ElectricCar" class gets all the properties and methods of the "Car" class and can also add its own properties and methods.

  1. Polymorphism is the ability of an object to take on many forms. It is achieved through method overloading and method overriding. Method overloading allows multiple methods to have the same name but different parameters. Method overriding allows a subclass to provide a specific implementation of a method that is already provided by its parent class. Polymorphism helps in creating more flexible and extensible code.

let's continue with the "Car" class example to explain Polymorphism in Java.

In our "Car" class example, we can demonstrate polymorphism by creating two objects, one of the "Car" class and one of the "ElectricCar" class, and calling a method on both objects that is defined in the "Car" class. The method we'll use for this example is the "drive(int miles)" method, which takes the number of miles as a parameter and prints a message indicating how far the car has driven.

Here's the updated "Car" class with the "drive(int miles)" method:

public class Car {
    private String make;
    private String model;
    private int year;
    private String color;
    private int mileage;

    public void setMake(String make) {
        this.make = make;
    }

    public String getMake() {
        return make;
    }

    public void setModel(String model) {
        this.model = model;
    }

    public String getModel() {
        return model;
    }

    public void setYear(int year) {
        this.year = year;
    }

    public int getYear() {
        return year;
    }

    public void setColor(String color) {
        this.color = color;
    }

    public String getColor() {
        return color;
    }

    public void setMileage(int mileage) {
        this.mileage = mileage;
    }

    public int getMileage() {
        return mileage;
    }

    public void start() {
        System.out.println("The " + make + " " + model + " has started.");
    }

    public void stop() {
        System.out.println("The " + make + " " + model + " has stopped.");
    }

    public void drive(int miles) {
        mileage += miles;
        System.out.println("The " + make + " " + model + " has driven " + miles + " miles.");
    }
}

Now, we can create two objects, one of the "Car" class and one of the "ElectricCar" class, and call the "drive(int miles)" method on both objects:

Car myCar = new Car();
myCar.setMake("Honda");
myCar.setModel("Civic");
myCar.setYear(2021);
myCar.setColor("Blue");
myCar.setMileage(10000);

ElectricCar myElectricCar = new ElectricCar();
myElectricCar.setMake("Tesla");
myElectricCar.setModel("Model S");
myElectricCar.setYear(2022);
myElectricCar.setColor("Red");
myElectricCar.setBatteryCapacity(100);
myElectricCar.setMaxRange(400);

Car[] cars = { myCar, myElectricCar };

for (Car car : cars) {
    car.drive(50);
}

In this code, we have created an array of type "Car" that contains both the "myCar" object and the "myElectricCar" object. We then loop through the array and call the "drive(int miles)" method on each object.

When we run this code, we get the following output:

The Honda Civic has driven 50 miles.
The Tesla Model S has driven 50 miles.

This demonstrates how polymorphism allows us to treat objects of different types as if they were the same type. In this case, we can call the "drive(int miles)" method on both the "Car" object and the "ElectricCar" object, even though they have different implementations of the method. This is because the "ElectricCar" class extends the "Car" class, so it inherits the "drive(int miles)" method from its parent class.

By using polymorphism in this way, we can write code that is more flexible and easier to maintain. For example, if we wanted to add a new type of car to our program, we could simply create a new subclass of "Car" and add it to the array of cars without having to change the code that loops through the array and calls the "drive(int miles)" method.

  1. Abstraction is the process of hiding the implementation details of a class and only exposing the essential features of the class. It is achieved through abstract classes and interfaces. An abstract class is a class that cannot be instantiated but can be used as a base class for other classes. An interface is a collection of abstract methods that can be implemented by any class. Abstraction helps in reducing complexity and makes the code more maintainable.

In the example of the "Car" class hierarchy, we could use abstraction to hide the details of how the cars actually work and expose only their basic functionality.

One way to do this is by defining an abstract class called "Vehicle" that defines the basic properties and methods that all vehicles must have. For example, a "Vehicle" might have a maximum speed, a weight, and a method for accelerating. However, the "Vehicle" class would not define the specific implementation of these methods, but instead, leave that to the subclasses that extend it.

Here's an example of how the "Vehicle" class might look like:

public abstract class Vehicle {
    private int maxSpeed;
    private int weight;

    public abstract void accelerate();

    // getters and setters for maxSpeed and weight
}

Notice that the "accelerate()" method is declared as abstract, which means that any class that extends "Vehicle" must provide its own implementation of this method. This is where the specific functionality of each type of vehicle would be implemented.

Now, we can extend the "Vehicle" class to create the "Car" and "ElectricCar" classes, as before, but this time we don't need to define the "maxSpeed" and "weight" properties or the "accelerate()" method. These are inherited from the "Vehicle" class, and we only need to implement the specific behavior of each type of car.

Here's an example of how the "Car" class might look like, now that it extends the "Vehicle" class:

public class Car extends Vehicle {
    public void accelerate() {
        // specific implementation of accelerating for a car
    }
}

By using abstraction in this way, we can create a more modular and extensible class hierarchy. We can define a common set of properties and methods in the "Vehicle" class, and then extend it to create specific types of vehicles, without having to duplicate the same code in each subclass. Additionally, we can write code that only depends on the "Vehicle" class, without having to know the specific details of each subclass, making the code more maintainable and easier to modify.

  1. Oracle Java Tutorials - Object-Oriented Programming Concepts: docs.oracle.com/javase/tutorial/java/concep..

  2. Java T Point - Java OOPs Concepts: javatpoint.com/java-oops-concepts

  3. GeeksforGeeks - Object-Oriented Programming (OOPs) Concept in Java: geeksforgeeks.org/object-oriented-programmi..

  4. Oops Concept By Kunal Kushwaha:https://www.youtube.com/playlist?list=PL9gnSGHSqcno1G3XjUbwzXHL8_EttOuKk

These links provide a mix of written tutorials, video tutorials, and practice exercises to help you understand OOPs concepts in Java. I hope you find them helpful!

If you found this helpful, please like and comment.