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

Classes and objects

Introduction to Classes and Objects

In Object-Oriented Programming (OOP), classes and objects form the foundational building blocks. Understanding these concepts is essential not only for cracking competitive exams but also for writing efficient, maintainable software in real-world applications.

Think of a class as a blueprint or a template-just like an architect's drawing for a house. It defines the structure and behavior but is not the house itself. An object, on the other hand, is the actual house built from that blueprint. You can build many houses (objects) from the same blueprint (class), each with its own unique features.

By mastering classes and objects, you gain the ability to model complex systems in a way that mirrors real life, making programming more intuitive and powerful.

Class Definition

A class is a user-defined data type that groups related data and functions. It defines attributes (also called data members) that represent the properties of the object, and methods (also called member functions) that define the behavior or actions the object can perform.

In simple terms, a class acts as a blueprint for creating objects. It specifies what data each object will hold and what operations can be performed on that data.

Class: Car Attributes (Data Members): - color : String - speed : int (km/h) - price : float (INR) Methods (Member Functions): + accelerate() + brake()

This diagram shows a simple class named Car with three attributes: color, speed, and price. It also has two methods: accelerate() and brake(), which define behaviors related to the car.

Object Instantiation

An object is a concrete instance of a class. When you create an object, you are instantiating the class, which means allocating memory to store the object's attributes and enabling access to its methods.

Each object has its own copy of the attributes defined by the class, allowing multiple objects to exist independently with different states.

graph TD    A[Define Class] --> B[Instantiate Object]    B --> C[Allocate Memory]    C --> D[Initialize Attributes]    D --> E[Object Ready for Use]

This flowchart shows the process from defining a class to creating an object ready for use in a program.

Attributes and Methods

Attributes and methods are the two core components of classes and objects:

Attributes (Data Members) Methods (Member Functions)
Store the state or properties of an object Define the behavior or actions of an object
Examples: color, speed, balance (INR) Examples: accelerate(), deposit(amount)
Hold values unique to each object Operate on attributes to change object state

Worked Examples

Example 1: Creating a Simple Class and Object Easy
Define a class Car with attributes color and speed. Create an object of this class and set the color to "Red" and speed to 60 km/h. Display these values.

Step 1: Define the class Car with attributes.

class Car {  String color;  int speed; // in km/h}    

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

Car myCar = new Car();myCar.color = "Red";myCar.speed = 60;    

Step 3: Display the object's attributes.

System.out.println("Color: " + myCar.color);System.out.println("Speed: " + myCar.speed + " km/h");    

Answer: The output will be:
Color: Red
Speed: 60 km/h

Example 2: Object State Modification Medium
Create a class BankAccount with an attribute balance (in INR). Implement a method deposit(amount) to add money to the balance. Show how to update the balance by depositing Rs.5000.

Step 1: Define the class with attribute and method.

class BankAccount {  double balance;  void deposit(double amount) {    balance = balance + amount;  }}    

Step 2: Create an object and initialize balance.

BankAccount account = new BankAccount();account.balance = 10000; // Initial balance Rs.10,000    

Step 3: Deposit Rs.5000 and display updated balance.

account.deposit(5000);System.out.println("Updated Balance: Rs." + account.balance);    

Answer: Updated Balance: Rs.15000

Example 3: Multiple Objects from One Class Medium
Using the Car class, create two objects representing two different cars with different colors and speeds. Show that each object maintains its own state.

Step 1: Define the class (same as before).

class Car {  String color;  int speed;}    

Step 2: Create two objects with different values.

Car car1 = new Car();car1.color = "Blue";car1.speed = 80;Car car2 = new Car();car2.color = "Green";car2.speed = 100;    

Step 3: Display attributes of both cars.

System.out.println("Car 1: " + car1.color + ", Speed: " + car1.speed + " km/h");System.out.println("Car 2: " + car2.color + ", Speed: " + car2.speed + " km/h");    

Answer:
Car 1: Blue, Speed: 80 km/h
Car 2: Green, Speed: 100 km/h

Example 4: Constructor Usage Medium
Define a class Car with a constructor to initialize color and speed at the time of object creation. Create an object with color "Black" and speed 90 km/h.

Step 1: Define the class with a constructor.

class Car {  String color;  int speed;  // Constructor  Car(String c, int s) {    color = c;    speed = s;  }}    

Step 2: Create an object using the constructor.

Car myCar = new Car("Black", 90);    

Step 3: Display the attributes.

System.out.println("Color: " + myCar.color);System.out.println("Speed: " + myCar.speed + " km/h");    

Answer:
Color: Black
Speed: 90 km/h

Example 5: Object Lifecycle and Memory Hard
Explain the lifecycle of an object in a program, including creation, usage, and destruction. Illustrate this with a class Session that prints messages when the object is created and destroyed (using constructor and destructor or equivalent).

Step 1: Define the class with constructor and destructor.

class Session {  // Constructor  Session() {    System.out.println("Session started.");  }  // Destructor (in Java, finalize is deprecated; use close or similar)  void close() {    System.out.println("Session ended.");  }}    

Step 2: Create and use the object.

Session userSession = new Session(); // Object created, constructor called// ... use the session ...userSession.close(); // Object cleanup, destructor equivalent called    

Explanation:

  • Creation: When new Session() is called, memory is allocated and the constructor runs, initializing the object.
  • Usage: The object can perform tasks or hold data during its lifetime.
  • Destruction: When the object is no longer needed, resources are released. In languages like C++, destructors run automatically. In Java, explicit methods like close() or try-with-resources are used.

Answer: The console output will be:
Session started.
Session ended.

Tips & Tricks

Tip: Remember classes are blueprints, objects are instances.

When to use: When distinguishing between definition and usage in questions.

Tip: Use real-world analogies like 'Car' or 'BankAccount' to understand attributes and methods.

When to use: When struggling to visualize abstract OOP concepts.

Tip: Focus on the difference between class-level and object-level data.

When to use: When questions involve static vs instance members.

Tip: Practice writing small code snippets to reinforce syntax and concepts.

When to use: Before attempting coding questions in exams.

Tip: Remember constructors initialize objects automatically.

When to use: When solving questions on object creation and initialization.

Common Mistakes to Avoid

❌ Confusing class with object.
✓ Class is a blueprint; object is an instance of that blueprint.
Why: Students often mix definition with instantiation due to similar terminology.
❌ Accessing object attributes without creating an object.
✓ Create an object first before accessing non-static members.
Why: Lack of understanding of memory allocation and object lifecycle.
❌ Forgetting to initialize attributes leading to default or garbage values.
✓ Use constructors or explicit initialization.
Why: Beginners overlook initialization, causing runtime errors.
❌ Mixing up method calls on class vs object.
✓ Call instance methods on objects, static methods on classes.
Why: Confusion between static and instance context.
❌ Assuming all objects share the same attribute values.
✓ Each object has its own copy of instance attributes.
Why: Misunderstanding of object state and memory allocation.
Key Concept

Classes and Objects

Classes define the blueprint including attributes and methods. Objects are instances of classes with their own state.

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
Classes and objects · 10 free messages
Ask me anything about this subtopic. You have 10 free messages this session — chat history isn't saved in preview.