DEV Community

Ayush Shrivastava for Mastering Backend

Posted on • Edited on • Originally published at masteringbackend.com

OOPs in Java: Principles, Concepts, and Real-World Examples

Object-Oriented Programming

OOP stands for object-oriented programming. It is a programming paradigm that revolves around the object rather than function and procedure. In other words, it is an approach for developing applications that emphasize on objects. An object is a real
word entity that contains data and code. It allows binding data and code together. here objects means real world entity like car, bike, atm etc.

Procedural Programming OOPS
programs are divided into parts called functions Programs are divided into objects
Overloading is not possible Overloading is possible
Inheritance is not possible Inheritance is possible
Data hiding is not present Data hiding is present
It follows a top-down approach It follows a bottom-up approach
It focuses on the process. It focuses on data.
Ex:- C, Pascal etc. Ex:- Java, C++, Python etc.

OOP Concepts in Java

Java follows Object-Oriented Programming (OOP), which is based on the following nine key concepts:

  1. Class – A blueprint for creating objects.
  2. Object – An instance of a class with state and behavior.
  3. Encapsulation – Hiding internal details and exposing only the necessary parts.
  4. Polymorphism – The ability to take multiple forms (method overloading & overriding).
  5. Inheritance – Acquiring properties and behaviors from a parent class.
  6. Abstraction – Hiding implementation details and showing only essential features.
  7. Association – A relationship between two classes without ownership.
  8. Composition – A strong association where one class owns another.

The Four Pillars of OOP

These are the core principles of OOP in Java:

  1. Encapsulation
  2. Inheritance
  3. Polymorphism
  4. Abstraction

Note: Concepts and pillars are different. Java has 8 main concepts, but only 4 pillars of OOP.

Benefits of OOP in Java

  1. Reusability – Write once, use multiple times to reduce redundancy.
  2. Data Redundancy – Avoids duplication by using shared class definitions.
  3. Code Maintenance – Easier to update and manage code efficiently.
  4. Security – Encapsulation and abstraction restrict unnecessary data access.
  5. Easy Troubleshooting – Objects simplify debugging and modification.
  6. Better Design – Stable base classes reduce errors in derived classes.

1. Class

A class in java a blueprint or template of an object from where an object is created. it doesn’t take space in the memory. It is a user-defined data type. Inside a class, we define variables, constants, functions. It is example of data binding. it is a logical entity.

Syntax

class ClassName {
    // Fields (variables)

    // Constructors

    // Methods
}
Enter fullscreen mode Exit fullscreen mode

2. Object

An Object is a real world entity that has attributes, behavior, and properties. It is referred to as an instance of the class. It contains member functions, variables that we have defined in the class. It occupies space in the memory. Different objects have
different states or attributes, and behaviors.

Object is a real world entity, every object have state and behavior state tell us how the object looks like and behavior tell us what the object does.

Syntax

ClassName objectName = new ClassName();  

Enter fullscreen mode Exit fullscreen mode
Class Object
It is a logical entity It is a real-world entity
It is a based on concepts. It is based on real world
It uses the keyword class when declared. It uses the new keyword to create an object.
It does not occupy space in the memory. It occupies space in the memory.
It is a data type that represents the blueprint of an
object. It is an instance of the class.

image.png

here car is a object is class and the Audi, BMW is a instance of that class. so all the properties and behavior of the class is also present in its instance.

class Car {

        // state
    private String color;
    private String type;
    private String brand;
    private int speed;

    // Constructor
    public Car(String color, String type, String brand) {
        this.color = color;
        this.type = type;
        this.brand = brand;
        this.speed = 0; // Initial speed
    }

    //behavior

    // Method to increase speed
    public void increaseSpeed(int increment) {
        speed += increment;
        System.out.println(brand + " speed increased to " + speed + " km/h");
    }

    // Method to apply brake
    public void applyBrake(int decrement) {
        speed -= decrement;
        if (speed < 0) speed = 0;
        System.out.println(brand + " speed reduced to " + speed + " km/h");
    }

    // Method to drive
    public void drive() {
        System.out.println(brand + " is driving at " + speed + " km/h");
    }

    // Method to display car details
    public void displayDetails() {
        System.out.println("Brand: " + brand + ", Type: " + type + ", Color: " + color);
    }

    public static void main(String[] args) {
        Car audi = new Car("Red", "Sedan", "Audi");
        Car bmw = new Car("Blue", "SUV", "BMW");

        audi.displayDetails();
        audi.increaseSpeed(50);
        audi.drive();
        audi.applyBrake(20);

        System.out.println();

        bmw.displayDetails();
        bmw.increaseSpeed(60);
        bmw.drive();
        bmw.applyBrake(30);
    }
}

Enter fullscreen mode Exit fullscreen mode

Output

Brand: Audi, Type: Sedan, Color: Red
Audi speed increased to 50 km/h
Audi is driving at 50 km/h
Audi speed reduced to 30 km/h

Brand: BMW, Type: SUV, Color: Blue
BMW speed increased to 60 km/h
BMW is driving at 60 km/h
BMW speed reduced to 30 km/h
Enter fullscreen mode Exit fullscreen mode

3. Encapsulation

The process of wrapping the data and code which is acting on the data together into a single unit is called as Encapsulation. we can achieve the encapsulation by creating the variables of class as private and create the getter and setter method as public to view and modify the variables. it is also known as data hiding.

Advantages

  • loosely coupled code.
  • Better access control & security.
package oops;

public class Encapsulation {
    public static void main(String[] args) {
        // creating the object
        Student student=new Student();

        // setting the value of the variables
        student.setAge(10);
        student.setName("Ayush");

        // Accessing the value of the variables
        System.out.println(student.getName());
        System.out.println(student.getAge());
    }
}

class Student{
    // variables as private
    private String name;
    private int age;

    // getter and setter
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}

Enter fullscreen mode Exit fullscreen mode

output-

Ayush
10
Enter fullscreen mode Exit fullscreen mode

here in this example we are creating the variables of the class as private so other classes can’t access theme this concept is called the encapsulation. and we provide the getter and method to modify and view the value of the variables. It provides you the control over the data. Suppose you want to set the value of age which should be greater than 18 only, you can write the logic inside the setter method. You can write the logic not to store the negative numbers in the setter methods.

4. Abstraction

The Process of hiding the internal implementation and shows only essential functionality to the user is known as abstraction. it is also known as the detail hiding. in java it is achieved through interface and abstract classes.

Advantages-

  • It increases security and confidentiality.

Example-

When we are driving a car if we want to stop the car than we just apply the break and the car speed will reduce, we don’t know how the car speed is reduce. and also there is no need to know as a driver how the things works in car. so we can say that break and other functionality of the car is abstract from us.

Similar in the cellphone how the call is made that is abstracted to us.

package oops;

public interface Car {
    void applyBreak();
    void start();
}

class BMW implements Car{
    public void applyBreak(){
        System.out.println("Applying break");
    }
    public void start(){
        System.out.println("Starting the car");
    }
}

Enter fullscreen mode Exit fullscreen mode

here in this example car is an interface applyBreak() and start() is a method of the Car interface and the class BMW implement the car interface so user only knows about the abstartion method that are applyBreak() and start() but don’t know about the internal implementations. here what we do we just hides the internal details of the class.

What are the interface and abstract class we learn in next article.

5. Polymorphism

Polymorphism is a combination of two words ploy means “Many” and morphism means “Form”. means same entity (method) having different behavior is called as a polymorphism.

Example-

  1. A person can be father, boy, teacher or can be a dancer, writer, programmer as well.
  2. water is liquid, solid or gas.

There are a tow types of polymorphism.

  1. Compile Time / static polymorphism
  2. Run Time/ Dynamic polymorphism

Compile Time polymorphism

A polymorphism which is achieved at compile time known as the compile time polymorphism.

Example- Method Overloading

Run Time polymorphism

A polymorphism which is achieved at run time known as the run time polymorphism.

Example- Method Overriding

Method Overloading

Two method is said to be overloaded if both the method having same name but variation in parameters. variation in parameters means. In method Overriding method signature is different.

  1. Number of parameters
  2. Position of parameters
  3. Data type of the parameters
class Calculator {
    // Method to add two integers
    int add(int a, int b) {
        return a + b;
    }

    // Method to add three integers (overloaded)
    int add(int a, int b, int c) {
        return a + b + c;
    }

    // Method to add two double numbers (overloaded)
    double add(double a, double b) {
        return a + b;
    }
}

public class MethodOverloadingExample {
    public static void main(String[] args) {
        Calculator calculator = new Calculator();

        int sum1 = calculator.add(5, 10);                 // Calls the first method
        int sum2 = calculator.add(5, 10, 15);             // Calls the second method
        double sum3 = calculator.add(2.5, 3.5);           // Calls the third method

        System.out.println("Sum1: " + sum1);
        System.out.println("Sum2: " + sum2);
        System.out.println("Sum3: " + sum3);
    }
}
Enter fullscreen mode Exit fullscreen mode

Here in this example, we have a Calculator class with overloaded add methods. The methods have the same name but different parameter lists (number and type of parameters). Depending on the number and types of arguments passed, the appropriate overloaded method is called.

Method Overriding

If child class method is not satisfied with its parent class method implementation than it override that implementation this concept is called as a overriding. It is only possible with Inheritance. In the runtime polymorphism it is decided which method is to be called parent class method or child class method. In method Overriding method signature is same.

class Vehicle {
    void start() {
        System.out.println("The vehicle starts");
    }
}

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

class Bike extends Vehicle {
    @Override
    void start() {
        System.out.println("The bike starts with a kick");
    }
}

public class Main {
    public static void main(String[] args) {
        Vehicle myVehicle = new Vehicle();
        myVehicle.start();  // Calls the start method in Vehicle

        Vehicle myCar = new Car();
        myCar.start();  // Calls the overridden start method in Car

        Vehicle myBike = new Bike();
        myBike.start();  // Calls the overridden start method in Bike
    }
}
Enter fullscreen mode Exit fullscreen mode

Here in this example Vehicle is a class having methods as start and bike and car is the subclass of that class where we override the start() method according to use case. The specific implementation is executed depending on the type of object at runtime.

6. Inheritance

Inheritance in Java is a mechanism in which one object acquires all the properties and behaviors of a parent object. The idea behind inheritance in Java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of the parent class. Moreover, you can add new methods and fields in your current class also.

Inheritance represents the IS-A relationship which is also known as a parent-child relationship.

Parent / super class - A class that properties and behaviors are acquired by the child class.

Child / sub class - A class that properties and behaviors are acquiring from the super class.

Advantages-

  1. Method overriding
  2. Code reuse

Types of Inheritance

  1. Multiple Inheritance (In java through class is not possible)
  2. Multilevel Inheritance
  3. Single level Inheritance
  4. hierarchical Inheritance
  5. Hybrid Inheritance (In java through class is not possible)

  6. Multiple Inheritance→ Single child class Acquiring the properties and behaviors of the super class.

  7. Multilevel Inheritance → Acquiring the properties and behaviors from another derived class.

  8. Hierarchical Inheritance → Two child classes are inheriting the properties and behavior from single super/ parent class.

image.png

  1. Multiple Inheritance → When one class Inherit multiple classes than this is known as the multiple inheritance. In java this is not possible through the class because of ambiguity or diamond problem but with help of interface we can achieve.
  2. Hybrid Inheritance → It is a combination of two and more than two inheritance. In java this is not possible through the class but with help of interface we can achieve.

image.png

Conclusion

Object-Oriented Programming (OOP) is a powerful approach to designing and organizing code that makes applications easier to build, manage, and scale. Through OOP concepts, developers create efficient, reusable, and maintainable code structures.

OOP is built on four fundamental pillars that govern how objects interact and function in a program:

  1. Encapsulation – Protects data by keeping it private within a class and exposing only what's necessary.
  2. Abstraction – Simplifies complex implementations by providing a clean interface for users.
  3. Inheritance – Enables classes to inherit properties and behaviors from other classes, promoting code reuse.
  4. Polymorphism – Allows a single action to behave differently in various contexts, enhancing code flexibility.

These concepts are essential for writing clean, structured code. For a deeper understanding, explore our dedicated articles on each pillar. Mastering OOP principles will improve your programming skills and help you tackle real-world problems more effectively .

Top comments (0)