👁 Preview — Study, Practice and Revise are open; mock tests and the rest of the syllabus unlock on subscription. Unlock all · ₹4,999
← Back to Programming Fundamentals
Study mode

Object-Oriented Programming

Introduction to Object-Oriented Programming (OOP)

In the world of programming, different approaches exist to solve problems and build software. One of the most powerful and widely used approaches is Object-Oriented Programming, commonly called OOP. Unlike traditional procedural programming, which focuses on step-by-step instructions, OOP organizes software design around objects-real-world entities or concepts represented in code.

Why is OOP important? It helps programmers create modular, reusable, and maintainable code by mimicking how we naturally perceive the world: as objects with properties and behaviors. This approach simplifies complex software development and is the foundation of many modern programming languages like Java, C++, Python, and C#.

In this section, we will explore the core ideas of OOP, starting from the basics and gradually moving to advanced concepts, all explained with clear examples and diagrams to help you master the topic for your competitive exams.

Classes and Objects

At the heart of OOP are two fundamental concepts: classes and objects.

A class is like a blueprint or template. Think of it as a plan for creating something. For example, consider the idea of a Car. A class named Car defines what a car is in terms of its attributes (such as color, speed) and methods (actions it can perform, like start or stop).

An object is a specific instance of a class. If the class is the blueprint, then the object is the actual car built from that blueprint. Each object has its own set of attribute values but shares the structure defined by the class.

For example, you might have two car objects:

  • Car1: color = red, speed = 100 km/h
  • Car2: color = blue, speed = 80 km/h

Both are cars but have different attribute values.

Class: Car Attributes: - color - speed Methods: - start() - stop() Object: Car1 color = red speed = 100 km/h Object: Car2 color = blue speed = 80 km/h

Attributes and Methods

Attributes (also called properties or fields) are variables that hold data related to an object. For example, a Car has attributes like color and speed.

Methods are functions defined inside a class that describe the behaviors or actions an object can perform. For example, start() and stop() are methods that control a car's movement.

Encapsulation

Encapsulation is the concept of bundling data (attributes) and methods that operate on that data into a single unit - the class - and controlling access to that data. It helps protect the internal state of an object from unintended interference and misuse.

Access to class members (attributes and methods) is controlled using access modifiers. The common access modifiers are:

  • Private: Accessible only within the class itself.
  • Protected: Accessible within the class and its subclasses (derived classes).
  • Public: Accessible from anywhere.

This control ensures that sensitive data is hidden and can only be accessed or modified through well-defined interfaces (methods), maintaining data integrity.

Access Modifiers and Their Accessibility
Access Modifier Within Class Within Subclass Outside Class
Private Yes No No
Protected Yes Yes No
Public Yes Yes Yes

Inheritance

Inheritance is a mechanism where a new class, called the child class or subclass, acquires the properties and behaviors (attributes and methods) of an existing class, called the parent class or superclass. This allows code reuse and establishes a natural hierarchy.

For example, consider a parent class Vehicle with attributes like speed and methods like move(). Two child classes, Car and Bike, can inherit these features and also add their own specific attributes or methods.

classDiagram    Vehicle <|-- Car    Vehicle <|-- Bike    class Vehicle {        +int speed        +void move()    }    class Car {        +int numberOfDoors        +void openTrunk()    }    class Bike {        +bool hasCarrier        +void ringBell()    }

Types of Inheritance:

  • Single Inheritance: One child inherits from one parent.
  • Multilevel Inheritance: A class inherits from a child class, forming a chain.

Polymorphism

Polymorphism means "many forms." In OOP, it allows methods to behave differently based on the context, even if they share the same name. This makes programs more flexible and extensible.

There are two main types of polymorphism:

  • Method Overloading: Multiple methods in the same class share the same name but have different parameter lists (different number or types of parameters).
  • Method Overriding: A subclass provides a specific implementation of a method that is already defined in its superclass, using the same method signature.
Comparison: Method Overloading vs. Method Overriding
Feature Method Overloading Method Overriding
Definition Same method name, different parameters in the same class Subclass provides new implementation of superclass method
Class Relationship Within the same class Between superclass and subclass
Purpose To perform similar tasks with different inputs To change or extend behavior of inherited methods
Example print(int x), print(String s) Subclass overrides print() method of superclass

Abstraction

Abstraction is the process of hiding complex implementation details and showing only the essential features to the user. It helps reduce complexity and allows the programmer to focus on what an object does instead of how it does it.

In OOP, abstraction is achieved using abstract classes and interfaces:

  • Abstract Class: A class that cannot be instantiated directly and may contain abstract methods (methods without implementation). Subclasses provide concrete implementations.
  • Interface: A contract that defines a set of methods without implementation. Classes that implement the interface must provide method bodies.

Abstraction allows programmers to design flexible and extensible systems.

Worked Examples

Example 1: Creating a Class and Object Easy
Define a class named Book with attributes title and author, and a method displayDetails() that prints these details. Create an object of this class and call the method.

Step 1: Define the class Book with attributes and method.

class Book {  String title;  String author;  void displayDetails() {    System.out.println("Title: " + title);    System.out.println("Author: " + author);  }}    

Step 2: Create an object of Book and assign values.

Book myBook = new Book();myBook.title = "Introduction to OOP";myBook.author = "John Doe";    

Step 3: Call the method to display details.

myBook.displayDetails();    

Answer: The output will be:
Title: Introduction to OOP
Author: John Doe

Example 2: Implementing Inheritance Medium
Create a parent class Animal with a method sound() that prints "Animal makes a sound". Create a subclass Dog that inherits from Animal and adds a method bark() that prints "Dog barks". Demonstrate calling both methods from a Dog object.

Step 1: Define the parent class Animal.

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

Step 2: Define the subclass Dog that inherits Animal.

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

Step 3: Create a Dog object and call methods.

Dog myDog = new Dog();myDog.sound(); // inherited methodmyDog.bark();  // subclass method    

Answer: The output will be:
Animal makes a sound
Dog barks

Example 3: Method Overloading Medium
Define a class Calculator with two methods named add: one that adds two integers and another that adds three integers. Demonstrate calling both methods.

Step 1: Define the Calculator class with overloaded methods.

class Calculator {  int add(int a, int b) {    return a + b;  }  int add(int a, int b, int c) {    return a + b + c;  }}    

Step 2: Create an object and call both methods.

Calculator calc = new Calculator();int sum1 = calc.add(10, 20);int sum2 = calc.add(5, 15, 25);    

Step 3: Print the results.

System.out.println("Sum1: " + sum1);System.out.println("Sum2: " + sum2);    

Answer: The output will be:
Sum1: 30
Sum2: 45

Example 4: Method Overriding Medium
Create a superclass Shape with a method draw() that prints "Drawing Shape". Create a subclass Circle that overrides draw() to print "Drawing Circle". Show how calling draw() on a Circle object uses the overridden method.

Step 1: Define the superclass Shape.

class Shape {  void draw() {    System.out.println("Drawing Shape");  }}    

Step 2: Define the subclass Circle overriding draw().

class Circle extends Shape {  @Override  void draw() {    System.out.println("Drawing Circle");  }}    

Step 3: Create a Circle object and call draw().

Circle c = new Circle();c.draw();    

Answer: The output will be:
Drawing Circle

Example 5: Using Encapsulation with Access Modifiers Medium
Define a class Student with a private attribute rollNumber and public getter and setter methods to access and modify it. Show how encapsulation protects the attribute.

Step 1: Define the Student class with private attribute.

class Student {  private int rollNumber;  public int getRollNumber() {    return rollNumber;  }  public void setRollNumber(int rollNumber) {    if (rollNumber > 0) {      this.rollNumber = rollNumber;    } else {      System.out.println("Invalid roll number");    }  }}    

Step 2: Create an object and use getter/setter.

Student s = new Student();s.setRollNumber(25);System.out.println("Roll Number: " + s.getRollNumber());    

Step 3: Attempt to set an invalid roll number.

s.setRollNumber(-5); // Should print error message    

Answer: The output will be:
Roll Number: 25
Invalid roll number

Formula Bank

Class-Object Relationship
\[ \text{Object} = \text{Instance of Class} \]
where: Object is a concrete entity created using the Class blueprint
Method Overloading Condition
\text{Same method name} + \text{Different parameter list}
Used to perform similar operations with different inputs
Method Overriding Condition
\text{Subclass method signature} = \text{Superclass method signature}
Used to provide specific implementation in subclass

Tips & Tricks

Tip: Remember the four pillars of OOP as "EIPA" - Encapsulation, Inheritance, Polymorphism, Abstraction.

When to use: For quick recall of core OOP concepts during exams.

Tip: Use real-world analogies like Car or Book classes to visualize objects and classes.

When to use: To understand abstract concepts more concretely.

Tip: For method overloading, focus on different parameter lists; for overriding, focus on inheritance and same method signature.

When to use: To quickly differentiate between overloading and overriding in questions.

Tip: Always use access modifiers to avoid common mistakes related to data hiding.

When to use: When designing classes or answering questions on encapsulation.

Tip: Practice writing small code snippets to reinforce concepts rather than memorizing definitions.

When to use: During exam preparation to improve problem-solving skills.

Common Mistakes to Avoid

❌ Confusing method overloading with method overriding
✓ Remember: Overloading is within the same class with different parameters; overriding requires inheritance and same method signature.
Why: Both involve methods with the same name but differ in context, causing confusion.
❌ Not using access modifiers leading to poor encapsulation
✓ Use private for attributes and public getter/setter methods to control access.
Why: Students often forget data hiding principles and make attributes public, risking data integrity.
❌ Trying to instantiate abstract classes or interfaces
✓ Abstract classes and interfaces cannot be instantiated directly; they must be subclassed or implemented.
Why: Misunderstanding the purpose of abstraction leads to this error.
❌ Ignoring the difference between class variables and instance variables
✓ Remember: Class variables are shared among all objects; instance variables belong to individual objects.
Why: Confusion arises due to similar naming and usage.
❌ Forgetting to call the superclass constructor in inheritance
✓ Explicitly call the superclass constructor if needed to initialize inherited attributes.
Why: Students overlook constructor chaining in inheritance, leading to incomplete initialization.
Key Concept

Four Pillars of Object-Oriented Programming

The foundation of OOP concepts that enable modular and reusable code.

✨ AI exam tools — try them free (included in every plan)
Tip: select any text above to Explain / Example / Simplify it.
Curated videos per subtopic
Top YouTube explainers, AI-ranked for your exam and language. Unlocks with subscription.
Unlock

Try Practice next.

Progress tracking is paywalled — subscribe to mark subtopics as understood and save your streak.

Go to practice →
Ask a doubt
Object-Oriented Programming · 10 free messages
Ask me anything about this subtopic. You have 10 free messages this session — chat history isn't saved in preview.