OOP Concepts and Examples That Every Programmer Should Know

In this article, we will cover the basic concepts around Object-Oriented Programming and discuss the commonly used terms: Abstraction, Encapsulation, Inheritance, and Polymorphism.

To begin with, OOP is a programming methodology that requires the programmers to create objects and use them throughout the program within the functions that require such objects for their operation. The reason why the OOPs concept is used extensively in java is that it allows the reusability of code while maintaining security. 

Check out our free courses to get an edge over the competition.

Explore Our Software Development Free Courses

Before we talk about the four pillars of object-oriented programming let us familiarize ourselves with the generic terms that we hear very often when using any of the object-oriented languages: Java, python, C++. 

Check out upGrad: Full Stack Development Bootcamp (JS/MERN)

Demystifying OOP: A Comprehensive Guide with Real-World Examples


Object-Oriented Programming (OOP) stands as a towering figure in the programming landscape, organizing code into reusable and modular components for unmatched efficiency and maintainability. Let’s embark on a journey to dissect its core concepts and delve into object oriented programming examples in oops, oops concepts examples, ensuring all our bases are covered without compromising on the richness of information.



Abstraction: Imagine viewing a car; you grasp its functionality (transport) without delving into the intricate mechanics under the hood. Abstraction embodies this, exposing an object’s essential features while concealing its complex implementation details. Think of it as focusing on the “what” rather than the “how” of an object.

Encapsulation: Picture a secure vault housing valuables. Encapsulation mirrors this concept, bundling data and the methods that operate on it within a single unit (class). This safeguards internal data from external interference, ensuring its integrity and security. Imagine building a fortress around your valuable data, accessible only through designated entry points.

Inheritance: Consider a family lineage where children inherit traits from their parents. Inheritance in OOP follows a similar principle, enabling the creation of new classes (child classes) that acquire properties and behaviors from existing ones (parent classes). This promotes code reuse and fosters hierarchical relationships, just like children inheriting knowledge and skills from their parents.

Polymorphism: Imagine an actor playing diverse roles. Polymorphism embodies this flexibility, allowing objects to exhibit different behaviors based on their context or data type. It supports method overriding and overloading, enhancing code adaptability and extensibility. Think of a single object wearing different hats and performing different actions depending on the context.


A class is a collection of objects that defines a set of properties that is common to all objects of a particular type. It can also be called a blueprint for creating objects. A class entails the following components:

Class name: The name given to a class starting with a capital alphabet.

Modifiers: Based on the functionality of the class modifiers can either be public, private or default.

Body: The class body contains all the codes on the objects present in the class. This could range from declaring any variables or creating any constructor or methods that contain the functioning of an object. 

Check out upGrad: Java Bootcamp

Explore our Popular Software Engineering Courses

upGrad’s Exclusive Software and Tech Webinar for you –

SAAS Business – What is So Different?



An object is defined as an instance of a class and contains real-life entities. For instance, for a class called Animals, Its objects will be a cat, dog, elephant et al. Each object has its own identity, attribute, and behaviour. The code below depicts the use of class, object, and method while programming in the java language. 


Methods are defined within a class and are used to perform a specific function. The method may or may not contain an input parameter. The code below depicts the use of class, object, and method while programming in the java language.

In the above code, Player is the name given to our class, whereas runs is a parameter passed in the method Batsman which returns the runs scored by him when called via an object called myobj. 

Access Modifiers

The access modifiers in Java defines the accessibility or extent of a method or constructor or the class. The four types of access modifiers are:

  1. Public: The code written within a class is accessible to other classes. 
  2. Private: The code written is only accessible within that specific class. 
  3. Default: The code written is accessible within the same package. 
  4. Protected: The code is accessible within a package and also through a subclass. In the absence of a child class, the code cannot be accessed.

Now let’s proceed and talk about the crux of object-oriented programming. 

In-Demand Software Development Skills


The term inheritance refers to inheriting the properties of one class to another. The properties refer to the attributes and methods of the parent class. The parent class is that class whose properties need to be inherited by other classes. The classes that inherit the properties of the parent class are called the child class or subclass. To inherit the properties of the parent class into the child class, a keyword called extends is used. 

In the above example, the Sponsor is the parent class with the owner being its attribute. We have created a subclass called Team that inherits the parent class- Sponsor. We have created an object of Team that can access the properties of the parent class. The output of the above code is:


As the name suggests- Polymorphism is the ability of a variable or a function to exist in multiple forms. Polymorphism allows the programmer to perform different tasks using the same variable or function. A real-life example of polymorphism would be- consider an open ground, now this ground can be used for playing sports.

Besides, it could also be used to organize weddings and concerts. Lastly, the same ground can be used for parking vehicles. From this, we can infer that a single variable can have multiple implementations depending upon its usage. 

The polymorphism we usually come across two terms namely- Method overloading and Method overriding.

In Method Overloading, a single method can be used in numerous ways and perform different functions. The methods will have the same name but different parameters can be used as input. 

In Method Overriding, the method of the parent class can be overridden by the child class. With this, the same method can perform differently when invoked by the parent class and by the child class. 

An example of the polymorphism is shown below:

In this example, using the same method we can perform multiple tasks. The same method Voice when used in Bird would output “Turr Turr” and when used with Duck will output “Quack Quack”. The snapshot of output is shown below-


Abstraction is the process of hiding certain data from the users and showing only the required information to them. For instance, while driving a car, we are not concerned about internal functions or mechanisms. What is shown to us are the speed at which the car is being driven and the litres of petrol available. All the other marginalized data are not displayed to the driver. 

The abstract keyword is used for methods and classes while performing abstraction. For an abstract class, we cannot create an object while the abstract method should not include a body. If any of the two rules are violated, the output will generate an error. 

Here, we have created an object of the subclass- Duck which is inherited from the main class- Bird. The output is shown below:


Encapsulation is the process of binding the code and the data together into a single unit. Here, the variables of a class are hidden from other classes (by using the keyword private) but can only be accessed through a member function. Setter and getter functions are used to access the private variables of a class that is abstract. 

Until now, we have covered anything and everything that is related to object-oriented programming using Java. Before we conclude, let us look at some of the advantages of the OOP concept.

  1. The code can easily be reused and therefore saves a lot of time and cost for the development of codes.
  2. It helps in designing the code in a well-structured manner so that any new programmer does not have to spend long hours to understand the code.
  3. Besides helping users in writing code efficiently, it makes sure that security is not compromised. 

Checkout: OOPs Interview Questions & Answers

Learn Software Courses online from the World’s top Universities. Earn Executive PG Programs, Advanced Certificate Programs, or Masters Programs to fast-track your career.

Read our Popular Articles related to Software Development

Advanced OOP Concepts in Action:

Composition: Think of building a complex robot using simpler components like wheels and sensors. Composition involves creating intricate objects by combining simpler ones, promoting code reuse and flexibility. Imagine constructing a complex system by assembling smaller, well-defined building blocks.

Interfaces: Imagine a contract outlining specific tasks. Interfaces define similar contracts, specifying methods that a class must implement. This enables loose coupling between classes, facilitating interchangeable implementations and code extensibility. Think of interfaces as standardized agreements that ensure different components work together seamlessly.

Dependency Injection: Picture delegating tasks to specialists instead of handling them yourself. Dependency injection follows this approach, injecting dependencies into a class rather than creating them internally. It promotes decoupling, testability, and code flexibility. Imagine outsourcing specific tasks to experts, resulting in a cleaner and more manageable codebase.

Exploring Key Concepts with Real-Time Examples

Let’s dive deeper into fundamental concepts of Object-Oriented Programming (OOP) by exploring real-world examples that illustrate these concepts in action.

  1. Object Example in OOP:

In OOP, objects are instances of classes that encapsulate data and behavior. Let’s consider a real-world example of a “Car” object:


Copy code

// Class definition

class Car {

// Data members

String model;

String color;

int year;

// Constructor

public Car(String model, String color, int year) {

this.model = model;

this.color = color;

this.year = year;


// Method to display car details

public void displayDetails() {

System.out.println(“Model: ” + model);

System.out.println(“Color: ” + color);

System.out.println(“Year: ” + year);



// Creating an object of Car class

public class Main {

public static void main(String[] args) {

Car myCar = new Car(“Toyota Camry”, “Blue”, 2022);




In this example, “myCar” is an object of the “Car” class, encapsulating data such as model, color, and year, along with behavior to display car details.

  1. Abstraction in OOP with Example:

Abstraction focuses on representing essential features while hiding complex implementation details. Let’s illustrate abstraction with a real-time example of a “Shape” class:


Copy code

// Abstract class for Shape

abstract class Shape {

// Abstract method to calculate area

abstract double calculateArea();


// Concrete class Rectangle inheriting Shape

class Rectangle extends Shape {

double length;

double width;

// Constructor

public Rectangle(double length, double width) {

this.length = length;

this.width = width;


// Implementation of abstract method


double calculateArea() {

return length * width;



// Main class

public class Main {

public static void main(String[] args) {

// Creating an object of Rectangle

Rectangle rectangle = new Rectangle(5, 3);

System.out.println(“Area of Rectangle: ” + rectangle.calculateArea());



In this example, the “Shape” class serves as an abstraction, defining a common interface for shapes, while “Rectangle” provides a concrete implementation. The complex details of calculating area are abstracted away from the user.

  1. Class in OOP with Example:

A class is a blueprint for creating objects. Let’s consider a class “Student” with attributes like name and age:


Copy code

// Class definition for Student

class Student {

// Data members

String name;

int age;

// Constructor

public Student(String name, int age) { = name;

this.age = age;


// Method to display student details

public void displayDetails() {

System.out.println(“Name: ” + name);

System.out.println(“Age: ” + age);



// Main class

public class Main {

public static void main(String[] args) {

// Creating an object of Student class

Student student = new Student(“John”, 20);




In this example, “Student” is a class encapsulating attributes and behavior to represent student entities.

  1. Encapsulation in Java with Real-Time Example:

Encapsulation involves bundling data and methods within a single unit (class) to restrict access from the outside. Let’s consider a real-time example of encapsulation with a “BankAccount” class:


Copy code

// Class definition for BankAccount

class BankAccount {

// Private data members

private double balance;

// Constructor

public BankAccount(double balance) {

this.balance = balance;


// Method to deposit money

public void deposit(double amount) {

balance += amount;

System.out.println(amount + ” deposited successfully.”);


// Method to withdraw money

public void withdraw(double amount) {

if (balance >= amount) {

balance -= amount;

System.out.println(amount + ” withdrawn successfully.”);

} else {

System.out.println(“Insufficient balance.”);



// Method to display balance

public void displayBalance() {

System.out.println(“Current Balance: ” + balance);



// Main class

public class Main {

public static void main(String[] args) {

// Creating an object of BankAccount class

BankAccount account = new BankAccount(1000);






In this example, the “balance” variable is encapsulated within the “BankAccount” class, accessible only through designated methods like deposit and withdraw, ensuring data integrity and security.

Unlocking the Benefits of OOP:

Code Reusability: Leverage inheritance and composition to create new functionalities from existing code, saving you time and effort. Imagine having pre-built components that you can readily assemble to create new software systems.

Modularity: Break down code into well-defined components (classes and objects) for easier understanding, maintenance, and scalability. Think of organizing your code into neatly labeled boxes, making it easier to find and update specific parts.

Abstraction and Encapsulation: Simplify code comprehension and enhance security by hiding implementation details and controlling data access. Imagine providing a simplified user interface, hiding the complex inner workings of the system.

Flexibility and Extensibility: Easily adapt and customize existing features without modifying the original codebase, thanks to polymorphism, inheritance, and interfaces. Imagine having a system that can readily adapt to new requirements without starting from scratch.

Security: Encapsulation safeguards sensitive data by restricting direct access and exposing it only through controlled methods. Imagine keeping your valuable information secure within a protected vault.

Potential Drawbacks to Consider:

Learning Curve: Grasping concepts like inheritance and polymorphism can be initially challenging, especially for beginners. It takes time and practice to become proficient in this new way of thinking about code.

Overhead: Creating and managing objects, dynamic dispatch, and method calls can introduce additional memory and processing resource usage, potentially impacting performance in resource-constrained environments. There can be some trade-offs to consider in terms of efficiency.

Complexity: Overly complex inheritance hierarchies and intricate class relationships can lead to convoluted and tightly coupled code, posing challenges for understanding, maintaining, and debugging. Keeping things organized and well-structured is crucial to avoid complexity pitfalls.

Overuse of Design Patterns: Excessive reliance on design patterns and abstraction in oops can result in overly abstract and convoluted codebases, potentially reducing readability. It’s important to strike a balance between using design patterns effectively and maintaining code clarity.

Performance: In performance-critical applications, the overhead associated with OOP might not be optimal compared to alternative paradigms. Consider the specific needs of your project when choosing the right programming approach.

OOP vs. Other Programming Styles: A Comparative Glimpse

OOP stands out from its peers, procedural and functional programming, in several key ways:

Procedural Programming:

Focus: Procedures (functions) that manipulate data stored in variables.

Execution: Linear flow, emphasizes procedural abstraction.

Example: Calculating area of different shapes using functions based on shape and dimensions.

Functional Programming:

Focus: Functions as first-class citizens, composing functions to transform data through immutable values.

Emphasis: Higher-order functions, recursion, pure functions.

Example: Calculating area of shapes using functions like area_rectangle and area_circle.

Key Differences from OOP:

Data: Often immutable in functional programming, mutable in OOP.

State: Functional programming discourages side effects and mutable state, OOP allows for them.

Paradigm Shift: Procedural to object-oriented vs. imperative to declarative.

Real-World OOP Examples:

Python OOP Examples:

Bank Account Management: Classes for accounts, customers, transactions (encapsulation, inheritance).

Game Development: Classes for characters, weapons, enemies (polymorphism, composition).

C# oops concepts with examples:

Library Management System: Classes for books, authors, users (abstraction, interfaces).


E-commerce Application: Classes for products, orders, users (encapsulation, polymorphism, inheritance).


Each paradigm has strengths and weaknesses.

Choice depends on project requirements, team expertise, performance considerations.

Understanding different paradigms empowers informed decisions in software development.


To conclude, in this blog we have covered the basic concepts of OOPs. These concepts are used extensively in industry and other applications. In order to become a proficient programmer, one should have a solid grasp of these concepts. In the upcoming blogs, we will uncover several other essential programming concepts that will help you develop expertise in this domain. 

If you’re interested to learn more about full-stack software development, check out upGrad & IIIT-B’s Executive PG Program in Full-stack Software Development which is designed for working professionals and offers 500+ hours of rigorous training, 9+ projects and assignments, IIIT-B Alumni status, practical hands-on capstone projects & job assistance with top firms.]

What is a factorial?

A factorial is a mathematical operation that counts the product of a given number and all the numbers below it. A factorial is a product that indicates how many times a number is multiplied by one. For example, the factorial of 5 is 5x4x3x2x1, which is equal to 120. The factorial of 1 is 1 and the factorial of 0 is also 1. The program to find a factorial of a number is the most commonly asked interview question and is something that should be on the tips of your hand.

How to write a factorial recursion program?

Factorial of a number n is defined as n! = 1 × 2 × 3 × 4 × … × n. Factorial of 5 is 120. The factorial function is defined as factorial(5) = 120. A recursive function is a function which calls itself. This is an example of a factorial function in recursive style factorial(n) = n * factorial(n - 1). Writing a factorial recursion program is very simple and the code is very similar to the iterative version. To write the iterative version, we use a variable called n and increment it by one and multiply it with the variable called prod, which keeps track of the successive values of n. The output value is also stored in the variable called prod. In the recursive version, you still use a variable called n. However, you don’t need a variable to store the value of prod and you can directly return prod from the function.

What is recursion in programming?

The word recursion is derived from the Latin word recurrere, which means to return. In most of the programming languages, a function which calls itself is called recursion. This looping process continues until the base case is reached, which is not defined in any recursive functions. Recursion is an effective technique for solving a problem in a structured and organized way. It is a good programming strategy. For instance, the Fibonacci series problem, the factorial problem, etc. can be solved in both iterative as well as recursive manner.

Want to share this article?

Become a Full Stack Developer

Leave a comment

Your email address will not be published. Required fields are marked *

Our Popular Software Engineering Courses

Get Free Consultation

Leave a comment

Your email address will not be published. Required fields are marked *

Get Free career counselling from upGrad experts!
Book a session with an industry professional today!
No Thanks
Let's do it
Get Free career counselling from upGrad experts!
Book a Session with an industry professional today!
Let's do it
No Thanks