Table of Contents

    Object

    Chapter 16.3

    Object in Object-Oriented Programming

    Learn what an object is in Object-Oriented Programming, how objects are created from classes, how they store data, perform actions, and represent real-world entities in software development.

    Introduction

    In Object-Oriented Programming, an object is one of the most important concepts. If a class is a blueprint, then an object is the actual thing created from that blueprint. Objects are used to represent real-world entities inside a program.

    For example, if Student is a class, then actual students such as Rahul, Ayesha, John, or Priya can be objects. Each object can store its own data and perform actions defined by the class.

    Object-Oriented Programming gets its name from the idea of building software using objects. Instead of writing only step-by-step instructions, we create objects that contain data and behavior. These objects interact with each other to complete different tasks in a program.

    "An object is an actual instance of a class that contains data and can perform actions."

    Simple Definition of Object

    An object is a real or logical entity created from a class. It has its own values for properties and can use the methods defined inside the class.

    In simple words, an object is:

    • A usable instance of a class.
    • A real entity in the program memory.
    • A container of data and behavior.
    • A representation of a real-world thing or concept.
    • A unit that can communicate with other objects.
    OBJECT CONCEPT
    Object = State + Behavior + Identity

    Every object generally has three important characteristics: state, behavior, and identity. These characteristics help us understand how objects work in Object-Oriented Programming.

    Important: A class defines the structure, but an object stores actual values and performs actual operations during program execution.

    Real-World Analogy of Object

    To understand objects clearly, imagine a house blueprint. The blueprint is only a plan. It shows where rooms, doors, windows, kitchen, and bathroom should be. But the blueprint itself is not a real house.

    When an actual house is built using that blueprint, it becomes a real object. Many houses can be created from the same blueprint, but each house can have different colors, owners, furniture, and locations.

    Object as a Real Instance

    A class is like a house blueprint. An object is like an actual house created from that blueprint. One blueprint can create many houses, and one class can create many objects.

    Real-World Concept Programming Concept Explanation
    House Blueprint Class Defines the design but does not represent an actual house.
    Actual House Object A real instance created from the blueprint.
    House Color, Owner, Address Object State Actual values stored inside the object.
    Open Door, Turn On Light Object Behavior Actions that the object can perform.

    Three Main Characteristics of an Object

    Every object in Object-Oriented Programming can be understood using three main characteristics: state, behavior, and identity.

    1

    State

    The data or current values stored inside an object

    The state of an object refers to the values of its properties at a particular time. For example, a student object may have name, roll number, course, marks, and grade.

    Example For a student object, state can be: name = "Rahul", rollNumber = 101, marks = 85.
    2

    Behavior

    The actions or operations an object can perform

    Behavior is defined by methods inside the class. Objects use these methods to perform tasks. For example, a student object may display details, calculate grade, or submit assignment.

    Example For a student object, behavior can be: displayDetails(), calculateGrade(), submitAssignment().
    3

    Identity

    A unique way to distinguish one object from another

    Identity means each object is separate from other objects, even if they are created from the same class. Two student objects may have the same structure, but they are still separate objects.

    Example student1 and student2 may both belong to the Student class, but they are two different objects.

    Object and Class Relationship

    A class and an object are directly related. A class defines the structure, and an object is created from that structure. A class is a logical design, while an object is an actual instance used in the program.

    RELATIONSHIP
    Class is used to create Object

    For example, Car can be a class. From this class, we can create many car objects such as car1, car2, and car3. Each object can have different values for brand, color, speed, and fuel level.

    Class Possible Objects Different Object Values
    Student student1, student2, student3 Different names, roll numbers, and marks
    Car car1, car2, car3 Different brands, colors, and speeds
    Book book1, book2, book3 Different titles, authors, and prices
    BankAccount account1, account2, account3 Different account numbers and balances
    Product product1, product2, product3 Different product names, prices, and stock quantities

    Why Do We Need Objects?

    Objects are needed because they allow us to represent real-world things inside a program. In real life, we work with objects every day: students, books, phones, cars, bank accounts, orders, employees, and products. Object-Oriented Programming allows us to model these real-world entities in software.

    Without objects, a large program may become a collection of unrelated variables and functions. This can make the program difficult to understand, maintain, and expand. Objects help group related data and behavior together.

    Without Objects

    • Data may be stored in many separate variables.
    • Functions may not clearly belong to any entity.
    • Large programs become harder to manage.
    • Real-world entities are difficult to represent.
    • Code duplication may increase.
    • Debugging and maintenance become more difficult.

    With Objects

    • Related data and actions stay together.
    • Real-world entities are represented naturally.
    • Code becomes more modular and organized.
    • Objects can be reused and modified easily.
    • Large systems can be divided into smaller parts.
    • Programs become easier to understand and maintain.

    Example: Student Object

    Let us understand objects with a student example. Suppose we have a class named Student. This class defines common properties such as name, roll number, course, and marks.

    Now we can create actual student objects from this class. Each object will have its own values.

    Object Name Name Roll Number Course Marks
    student1 Rahul 101 Programming Fundamentals 85
    student2 Ayesha 102 Programming Fundamentals 92
    student3 John 103 Programming Fundamentals 76

    All three objects are created from the same Student class, but each object stores different data. This is one of the main powers of Object-Oriented Programming.

    Basic Object Creation Concept

    Object creation means creating an actual instance from a class. The exact syntax depends on the programming language, but the basic concept is similar in most object-oriented languages.

    
    // Conceptual object creation
    
    ClassName objectName = new ClassName();
    

    In this structure:

    • ClassName is the name of the class.
    • objectName is the name of the object.
    • new is commonly used in many languages to create an object.
    • The object gets its own memory and can store its own data.
    Note: Some programming languages use different syntax for object creation, but the idea remains the same: an object is created from a class.

    Java Example of Object

    The following Java example shows how an object is created from a class and how it stores values.

    Prerequisites: To understand this example, you should know variables, data types, class, methods, object creation, and the main method in Java.
    
    class Student {
    
        String name;
        int rollNumber;
        int marks;
    
        void displayDetails() {
            System.out.println("Name: " + name);
            System.out.println("Roll Number: " + rollNumber);
            System.out.println("Marks: " + marks);
        }
    }
    
    public class Main {
        public static void main(String[] args) {
    
            // Creating an object of Student class
            Student student1 = new Student();
    
            // Assigning values to object properties
            student1.name = "Rahul";
            student1.rollNumber = 101;
            student1.marks = 85;
    
            // Calling object method
            student1.displayDetails();
        }
    }
    

    In this example, Student is the class and student1 is the object. The object stores values for name, rollNumber, and marks. The object also calls the displayDetails() method.

    JavaScript Example of Object

    JavaScript also supports objects and classes. The following example shows how to create an object from a class in JavaScript.

    Prerequisites: To understand this example, you should know JavaScript variables, classes, constructor, methods, and console output.
    
    class Student {
    
        constructor(name, rollNumber, marks) {
            this.name = name;
            this.rollNumber = rollNumber;
            this.marks = marks;
        }
    
        displayDetails() {
            console.log("Name: " + this.name);
            console.log("Roll Number: " + this.rollNumber);
            console.log("Marks: " + this.marks);
        }
    }
    
    // Creating an object
    const student1 = new Student("Ayesha", 102, 92);
    
    // Calling object method
    student1.displayDetails();
    

    In this JavaScript example, student1 is an object created from the Student class. The constructor initializes the object values when the object is created.

    Accessing Object Properties and Methods

    In many programming languages, we use the dot operator to access the properties and methods of an object. The dot operator connects the object name with the property or method name.

    DOT OPERATOR
    objectName.propertyName   |   objectName.methodName()
    
    // Accessing object properties
    
    student1.name = "Rahul";
    student1.marks = 85;
    
    // Calling object method
    
    student1.displayDetails();
    

    Here, student1.name accesses the name property of the object. student1.displayDetails() calls the method of the object.

    Multiple Objects from One Class

    One class can create many objects. Each object has the same structure but can contain different values. This makes classes reusable and objects useful for representing multiple real-world items.

    
    class Car {
    
        String brand;
        String color;
    
        void showCar() {
            System.out.println("Brand: " + brand);
            System.out.println("Color: " + color);
        }
    }
    
    public class Main {
        public static void main(String[] args) {
    
            Car car1 = new Car();
            car1.brand = "Toyota";
            car1.color = "Red";
    
            Car car2 = new Car();
            car2.brand = "Honda";
            car2.color = "Blue";
    
            car1.showCar();
            car2.showCar();
        }
    }
    

    In this example, car1 and car2 are two different objects created from the same Car class. Both objects have brand and color properties, but their values are different.

    Object Brand Color
    car1 Toyota Red
    car2 Honda Blue

    Object and Memory

    When an object is created, memory is allocated to store its data. Each object usually gets separate memory for its instance variables or properties. This means that changing data in one object does not automatically change data in another object.

    For example, if student1 and student2 are two objects, changing student1's marks will not change student2's marks because both objects store their own data separately.

    OBJECT MEMORY IDEA
    Each Object stores Its Own Data
    
    Student student1 = new Student();
    Student student2 = new Student();
    
    student1.marks = 85;
    student2.marks = 92;
    

    Here, student1 and student2 are separate objects. They are created from the same class, but they store different marks values.

    Object Communication

    In Object-Oriented Programming, objects can communicate with each other by calling methods. This is also known as message passing.

    For example, in an online shopping system, a Customer object may place an order. The Order object may calculate the total amount. The Payment object may process the payment. The Delivery object may update the shipping status.

    OBJECT COMMUNICATION
    Object A calls method of Object B
    
    // Conceptual object communication
    
    customer.placeOrder();
    
    order.calculateTotal();
    
    payment.processPayment();
    
    delivery.updateStatus();
    

    This type of communication helps divide a large system into smaller objects, where each object performs its own responsibility.

    Real-World Example: Objects in E-Commerce System

    In an e-commerce system, many objects work together to complete a shopping process. Each object represents a specific part of the system.

    Object Possible State Possible Behavior
    customer1 name, email, address login(), updateProfile(), placeOrder()
    product1 productName, price, stock displayProduct(), updateStock()
    cart1 items, totalAmount addItem(), removeItem(), calculateTotal()
    order1 orderId, orderDate, orderStatus confirmOrder(), cancelOrder(), trackOrder()
    payment1 amount, paymentMode, paymentStatus processPayment(), refundPayment()

    This example shows that an application is not just one big block of code. It can be designed as a group of objects that work together.

    Real-World Example: Bank Account Object

    A bank account object is a common example used to explain OOP. Each bank account object has its own account number, account holder name, and balance. It can also perform actions such as deposit, withdraw, and check balance.

    
    class BankAccount {
    
        String accountNumber;
        String accountHolderName;
        double balance;
    
        void deposit(double amount) {
            if (amount > 0) {
                balance = balance + amount;
            }
        }
    
        void withdraw(double amount) {
            if (amount <= balance) {
                balance = balance - amount;
            } else {
                System.out.println("Insufficient balance");
            }
        }
    
        void displayBalance() {
            System.out.println("Balance: " + balance);
        }
    }
    
    public class Main {
        public static void main(String[] args) {
    
            BankAccount account1 = new BankAccount();
    
            account1.accountNumber = "A101";
            account1.accountHolderName = "Rahul";
            account1.balance = 5000;
    
            account1.deposit(1000);
            account1.withdraw(1500);
            account1.displayBalance();
        }
    }
    

    Here, account1 is a BankAccount object. It stores account details and performs operations using methods.

    Class vs Object

    Class and object are connected, but they are not the same. A class is a blueprint, while an object is an actual instance created from that blueprint.

    Basis Class Object
    Meaning Blueprint or template. Actual instance created from a class.
    Nature Logical design. Real entity in program memory.
    Data Defines what data objects will have. Stores actual data values.
    Example Student student1, student2
    Memory Usually does not store individual object data. Stores actual values in memory.
    Usage Used to create objects. Used to perform operations.
    Quantity One class can define a type. Many objects can be created from one class.

    Object vs Variable

    A variable usually stores a single value, such as a number, text, or boolean. An object can store multiple related values and can also perform actions through methods.

    Basis Variable Object
    Purpose Stores a single value or reference. Stores related data and behavior.
    Example marks = 85 student1 contains name, roll number, marks, and methods.
    Complexity Simple data holder. More structured and powerful.
    Behavior Does not usually define actions by itself. Can perform actions using methods.

    Types of Objects in Programming

    Objects can represent different kinds of entities depending on the program. Some objects represent real-world things, while others represent logical parts of the application.

    Common Types of Objects

    • Real-world objects: Student, Car, Book, Employee, Customer.
    • Data objects: StudentRecord, ProductDetails, TransactionData.
    • Service objects: PaymentService, EmailService, ReportService.
    • Controller objects: Objects that manage flow between user input and program logic.
    • Utility objects: Objects that provide helper operations.
    • UI objects: Button, Form, Window, Menu, DialogBox.

    How to Identify Objects in a Problem

    To identify objects in a problem, read the problem statement carefully and look for important nouns. These nouns often represent possible classes or objects.

    OBJECT IDENTIFICATION RULE
    Important Nouns can become Objects or Classes

    For example, consider this problem statement:

    "A library system manages books, members, librarians, borrowing records, and fines."

    Possible objects in this system may include:

    • book1, book2, book3
    • member1, member2
    • librarian1
    • borrowRecord1
    • fine1

    Each object will have its own state and behavior depending on the class from which it is created.

    Advantages of Using Objects

    Objects provide many advantages in software development. They make applications easier to structure, understand, test, and maintain.

    Benefits of Objects

    • Objects help represent real-world entities naturally.
    • Objects group related data and behavior together.
    • Objects make code more organized and modular.
    • Objects allow multiple instances from one class.
    • Objects reduce code duplication when used properly.
    • Objects make large applications easier to maintain.
    • Objects support data protection through encapsulation.
    • Objects can communicate with other objects to complete tasks.
    • Objects help divide large systems into smaller manageable units.
    • Objects support reusable and scalable software design.

    Common Mistakes Beginners Make with Objects

    Beginners often make mistakes while learning objects. Understanding these mistakes early helps improve programming logic and OOP design.

    Common Mistakes

    • Confusing object with class.
    • Creating an object without understanding the class structure.
    • Using unclear object names like a, b, x, y.
    • Trying to access properties that do not exist.
    • Forgetting to initialize object values.
    • Making all object data public without control.
    • Creating too many objects unnecessarily.
    • Not understanding that each object stores separate data.

    Better Approach

    • Remember that a class is a blueprint and an object is an instance.
    • Understand class properties and methods before creating objects.
    • Use meaningful object names like student1, account1, product1.
    • Initialize object data properly using constructor or assignment.
    • Use methods to access or modify important data safely.
    • Create objects only when needed.
    • Remember that each object can have different data.
    • Practice using multiple objects from the same class.

    Best Practices for Working with Objects

    To write better object-oriented programs, we should follow some best practices while creating and using objects.

    Object Usage Best Practices

    • Use clear and meaningful object names.
    • Create objects only when they represent a meaningful entity or responsibility.
    • Initialize object data properly before using it.
    • Keep object data consistent and valid.
    • Use methods to perform operations on object data.
    • Avoid directly modifying sensitive data from outside the object.
    • Use constructors to set required initial values.
    • Keep each object focused on its responsibility.
    • Avoid creating unnecessary duplicate objects.
    • Understand how objects interact with one another in a system.

    Mini Practice Activity

    Try to identify possible objects, their state, and their behavior from the following scenarios. This practice will help you think in an object-oriented way.

    Scenario Possible Object Possible State Possible Behavior
    School Management student1 name, rollNumber, marks attendClass(), submitAssignment(), viewResult()
    Banking System account1 accountNumber, holderName, balance deposit(), withdraw(), checkBalance()
    Library System book1 title, author, availability borrowBook(), returnBook(), displayBook()
    Online Shopping product1 name, price, stock addToCart(), applyDiscount(), updateStock()
    Transport System car1 brand, color, speed start(), stop(), accelerate(), brake()

    Frequently Asked Questions

    1. What is an object in simple words?

    An object is an actual instance created from a class. It stores data and can perform actions using methods. For example, if Student is a class, then student1 is an object.

    2. Is an object the same as a class?

    No. A class is a blueprint or design, while an object is the actual instance created from that blueprint. A class defines structure, and an object stores actual values.

    3. Can one class create many objects?

    Yes. One class can create many objects. Each object follows the same structure but stores different data. For example, one Student class can create student1, student2, and student3.

    4. What does an object contain?

    An object contains state and behavior. State means object data or property values. Behavior means methods or actions that the object can perform.

    5. Why are objects important in OOP?

    Objects are important because they help represent real-world entities in software. They group data and behavior together, making programs more organized, reusable, and maintainable.

    6. What is object identity?

    Object identity means each object is unique and separate from other objects, even if they are created from the same class and have similar data.

    7. What is the difference between object state and object behavior?

    Object state refers to the values stored inside an object, such as name, price, or balance. Object behavior refers to actions the object can perform, such as displayDetails(), deposit(), or withdraw().

    Summary

    An object is a fundamental building block of Object-Oriented Programming. It is an actual instance created from a class. A class defines the structure, while an object stores actual data and performs actions.

    Objects help programmers represent real-world entities inside software systems. A student, car, book, product, bank account, order, and customer can all be represented as objects in a program.

    Every object generally has state, behavior, and identity. The state represents data, behavior represents actions, and identity makes each object unique. Objects make programs more modular, reusable, organized, and easier to maintain.

    Key Takeaway

    An object is an actual instance of a class. It contains state, performs behavior, and has a unique identity. Objects allow programmers to model real-world entities and build organized, reusable, and maintainable software.