Table of Contents

    Class

    Chapter 16.2

    Class in Object-Oriented Programming

    Learn what a class is in Object-Oriented Programming, why classes are needed, how they work, how they define objects, and how classes help organize real-world software systems.

    Introduction

    In Object-Oriented Programming, a class is one of the most fundamental concepts. If Object-Oriented Programming is based on objects, then a class is the design or blueprint from which those objects are created.

    A class defines the structure and behavior of objects. It tells what data an object will store and what actions the object can perform. Without a class, we cannot properly create structured objects in most object-oriented programming languages.

    For example, if we want to create many student records in a program, we can first create a Student class. This class can define common data such as name, roll number, marks, course, and grade. Then we can create multiple student objects from this class.

    "A class is a blueprint or template that defines the properties and behaviors of objects."

    Simple Definition of Class

    A class is a user-defined structure that groups related data and methods together. It acts as a plan for creating objects.

    In simple words, a class tells:

    • What information an object should contain.
    • What actions an object should perform.
    • How an object should be initialized.
    • How data and behavior are logically grouped.
    CLASS CONCEPT
    Class = Properties + Methods + Rules

    A class does not usually store actual data by itself. Instead, it defines the structure that objects will follow. Actual data is stored inside objects created from the class.

    Important: A class is not the actual object. It is only a blueprint. The actual usable item created from a class is called an object.

    Real-World Analogy of Class

    To understand class clearly, imagine a house plan. A house plan contains the design of the house such as number of rooms, doors, windows, kitchen, bathroom, and layout. But the plan itself is not a real house.

    Using the same house plan, many actual houses can be built. Each house may have different colors, furniture, owners, and locations, but all follow the same basic design.

    Class as a Blueprint

    A class is like a house blueprint. Objects are like actual houses created from that blueprint. One class can be used to create many objects.

    Real-World Concept Programming Concept Explanation
    House Plan Class Defines the structure but is not the actual house.
    Actual House Object Real usable item created from the plan.
    Rooms, Doors, Windows Properties Characteristics defined by the class.
    Open Door, Turn On Light Methods Actions that can be performed by the object.

    Class and Object Relationship

    A class and an object are closely related, but they are not the same. The class defines the structure, while the object is an actual instance created from that structure.

    For example, Student can be a class. From this class, we can create actual student objects such as Rahul, Ayesha, John, or Priya.

    RELATIONSHIP
    Class creates Object
    Class Possible Objects
    Student student1, student2, student3
    Car car1, car2, car3
    Book book1, book2, book3
    BankAccount account1, account2, account3
    Product product1, product2, product3

    Why Do We Need Classes?

    Classes are needed because they help us organize code in a meaningful and reusable way. Without classes, large programs can become difficult to manage because data and functions may be scattered everywhere.

    Classes allow developers to group related data and behavior together. This makes code easier to understand, modify, test, and reuse.

    Without Class

    • Data may be stored in many separate variables.
    • Functions may be scattered across the program.
    • Code becomes difficult to maintain.
    • Same logic may be repeated multiple times.
    • Large applications become harder to organize.
    • It becomes difficult to represent real-world entities.

    With Class

    • Related data and methods are grouped together.
    • Code becomes modular and organized.
    • Objects can be created easily from one blueprint.
    • Code can be reused in different parts of the program.
    • Real-world entities can be represented naturally.
    • Large applications become easier to maintain.

    Main Parts of a Class

    A class usually contains several important parts. Different programming languages may use different syntax, but the basic idea remains almost the same.

    Part of Class Meaning Example
    Class Name The name used to identify the class. Student, Car, Product
    Properties / Attributes Variables that store object data. name, rollNumber, price
    Methods Functions defined inside a class. displayDetails(), calculateTotal()
    Constructor Special method used to initialize an object. Setting initial values when object is created
    Access Modifiers Control the visibility of class members. public, private, protected

    Basic Structure of a Class

    The general structure of a class contains a class name, properties, and methods. The exact syntax changes from language to language, but the concept remains the same.

    
    // General conceptual structure of a class
    
    Class ClassName
    {
        // Properties or attributes
        property1
        property2
    
        // Methods or behaviors
        method1()
        {
            // statements
        }
    
        method2()
        {
            // statements
        }
    }
    

    In this structure, ClassName represents the name of the class. The properties define what data the object will contain. The methods define what actions the object can perform.

    Example: Student Class

    Let us create a conceptual Student class. A student has data such as name, roll number, course, and marks. A student can also perform actions such as displaying details and calculating grade.

    
    // Conceptual Student class
    
    Class Student
    {
        name
        rollNumber
        course
        marks
    
        displayDetails()
        {
            print name
            print rollNumber
            print course
            print marks
        }
    
        calculateGrade()
        {
            if marks >= 90
                return "A"
            else if marks >= 75
                return "B"
            else if marks >= 60
                return "C"
            else
                return "Fail"
        }
    }
    

    In this example, Student is a class. It defines four properties and two methods. From this class, we can create many student objects.

    Note: The above example is conceptual. It is written to explain the idea of a class, not to follow the exact syntax of one specific programming language.

    Properties in a Class

    Properties are variables declared inside a class. They represent the data or characteristics of an object. Properties are also called attributes, fields, or data members depending on the programming language.

    For example, in a Student class, the properties can be:

    • name
    • rollNumber
    • course
    • marks
    • grade
    Class Possible Properties
    Student name, rollNumber, marks, grade
    Car brand, model, color, speed, fuelLevel
    Book title, author, price, isbn
    BankAccount accountNumber, accountHolderName, balance
    Product productId, productName, price, stockQuantity

    Methods in a Class

    Methods are functions written inside a class. They define the behavior or actions of objects. A method can read object data, modify object data, perform calculations, or communicate with other objects.

    For example, in a BankAccount class, methods can be:

    • deposit()
    • withdraw()
    • checkBalance()
    • displayAccountDetails()
    
    // Conceptual BankAccount class
    
    Class BankAccount
    {
        accountNumber
        accountHolderName
        balance
    
        deposit(amount)
        {
            balance = balance + amount
        }
    
        withdraw(amount)
        {
            balance = balance - amount
        }
    
        checkBalance()
        {
            return balance
        }
    }
    

    Here, the class contains data and methods related to a bank account. This is one of the main advantages of using classes: related information and actions stay together.

    Constructor in a Class

    A constructor is a special method used to initialize an object when it is created. It helps set initial values for object properties.

    For example, when a new student object is created, we may want to immediately set the student's name, roll number, and course. A constructor helps us do that.

    CONSTRUCTOR PURPOSE
    Constructor initializes Object
    
    // Conceptual constructor example
    
    Class Student
    {
        name
        rollNumber
    
        Constructor Student(studentName, studentRoll)
        {
            name = studentName
            rollNumber = studentRoll
        }
    }
    

    In many programming languages, the constructor runs automatically when an object is created.

    Access Modifiers in a Class

    Access modifiers define how class members can be accessed from outside the class. They are useful for protecting data and controlling visibility.

    Common access modifiers include:

    Access Modifier Meaning Usage
    public Can be accessed from outside the class. Useful for methods that should be available to other parts of the program.
    private Can be accessed only inside the class. Useful for protecting sensitive data.
    protected Can be accessed inside the class and related child classes. Useful in inheritance-based designs.
    Important: Access modifiers support encapsulation by preventing direct unwanted access to important data.

    Class and Encapsulation

    A class supports encapsulation because it groups data and methods together. It can also restrict direct access to data using access modifiers.

    For example, in a BankAccount class, the balance should not be directly changed from outside the class. Instead, it should be updated through methods like deposit() and withdraw().

    Poor Design

    • Balance is directly accessible from outside.
    • Anyone can change the balance incorrectly.
    • There is no validation before updating data.
    • Data becomes unsafe and unreliable.

    Better Class Design

    • Balance is kept private.
    • Deposit and withdraw methods control updates.
    • Validation can be added inside methods.
    • Data becomes safer and more reliable.

    Java Example of Class

    The following example shows a simple class in Java. Java is a class-based object-oriented programming language, so classes are very important in Java.

    Prerequisites: To understand this example, you should know basic variables, data types, 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);
        }
    
        String calculateGrade() {
            if (marks >= 90) {
                return "A";
            } else if (marks >= 75) {
                return "B";
            } else if (marks >= 60) {
                return "C";
            } else {
                return "Fail";
            }
        }
    }
    
    public class Main {
        public static void main(String[] args) {
    
            Student student1 = new Student();
    
            student1.name = "Rahul";
            student1.rollNumber = 101;
            student1.marks = 85;
    
            student1.displayDetails();
    
            System.out.println("Grade: " + student1.calculateGrade());
        }
    }
    

    In this example, Student is a class. It contains three properties: name, rollNumber, and marks. It also contains two methods: displayDetails() and calculateGrade().

    JavaScript Example of Class

    JavaScript also supports classes. The class syntax in JavaScript provides a clean way to create objects with properties and methods.

    Prerequisites: To understand this example, you should know JavaScript variables, functions, objects, console output, and basic conditional statements.
    
    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);
        }
    
        calculateGrade() {
            if (this.marks >= 90) {
                return "A";
            } else if (this.marks >= 75) {
                return "B";
            } else if (this.marks >= 60) {
                return "C";
            } else {
                return "Fail";
            }
        }
    }
    
    const student1 = new Student("Ayesha", 102, 92);
    
    student1.displayDetails();
    
    console.log("Grade: " + student1.calculateGrade());
    

    In this example, the constructor initializes the student object with name, roll number, and marks. The object can then call its methods using the dot operator.

    Dot Operator and Class Members

    In many programming languages, the dot operator is used to access object properties and methods. The dot operator connects the object name with its member.

    DOT OPERATOR
    objectName.memberName
    
    // Accessing properties and methods
    
    student1.name = "Rahul";
    
    student1.displayDetails();
    

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

    Multiple Objects from One Class

    One of the biggest advantages of a class is that we can create multiple objects from a single class. Each object follows the same structure but stores its own separate data.

    
    // One class, multiple objects
    
    Student student1 = new Student();
    Student student2 = new Student();
    Student student3 = new Student();
    
    student1.name = "Rahul";
    student2.name = "Ayesha";
    student3.name = "John";
    

    All three objects are created from the same Student class, but each object can store different values. This makes classes highly reusable.

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

    Real-World Example: Product Class

    In an e-commerce application, a Product class can be used to represent products available in an online store. Each product may have a name, price, stock quantity, and category.

    
    // Conceptual Product class
    
    Class Product
    {
        productId
        productName
        price
        stockQuantity
    
        displayProduct()
        {
            print productName
            print price
            print stockQuantity
        }
    
        updateStock(quantity)
        {
            stockQuantity = stockQuantity + quantity
        }
    
        applyDiscount(discountAmount)
        {
            price = price - discountAmount
        }
    }
    

    From this Product class, we can create many product objects such as laptop, mobile, keyboard, and mouse. Each object will have its own product details.

    Real-World Example: Bank Account Class

    A BankAccount class is another excellent example of class usage. It can store account details and provide methods for deposit, withdrawal, and balance checking.

    
    // Conceptual BankAccount class
    
    Class BankAccount
    {
        accountNumber
        accountHolderName
        balance
    
        deposit(amount)
        {
            if amount > 0
                balance = balance + amount
        }
    
        withdraw(amount)
        {
            if amount <= balance
                balance = balance - amount
            else
                print "Insufficient balance"
        }
    
        checkBalance()
        {
            return balance
        }
    }
    

    This example shows how classes can combine data and rules together. The withdraw method checks whether the balance is sufficient before reducing the amount.

    Class Naming Rules and Best Practices

    Class names should be clear, meaningful, and easy to understand. A good class name tells what the class represents.

    Best Practices for Naming Classes

    • Use meaningful names such as Student, Product, Customer, or BankAccount.
    • Use singular nouns for class names because a class represents one type of object.
    • Follow the naming convention of the programming language.
    • In many languages, class names are written in PascalCase.
    • Avoid vague names such as Data, Info, Manager, or Things without clear meaning.
    • Do not use spaces in class names.
    • Avoid using special characters in class names.
    • Keep class names short but descriptive.
    Poor Class Name Better Class Name Reason
    Data StudentRecord StudentRecord clearly explains what data is stored.
    Thing Product Product clearly represents an item in a store.
    Info CustomerProfile CustomerProfile gives more specific meaning.
    ABC BankAccount BankAccount clearly describes the entity.

    Characteristics of a Good Class

    A good class should have a clear purpose. It should represent one meaningful concept and should not try to do too many unrelated tasks.

    Good Class Design Principles

    • A class should represent a clear real-world or logical entity.
    • A class should have a meaningful name.
    • A class should contain related properties and methods.
    • A class should follow the single responsibility idea.
    • A class should protect important data when needed.
    • A class should be reusable where possible.
    • A class should avoid unnecessary complexity.
    • A class should make the program easier to understand.

    Class vs Object

    Beginners often confuse class and object. The difference is very important. 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.
    Existence Logical design. Real entity in program memory.
    Data Defines what data will exist. Stores actual data values.
    Example Student student1, student2
    Memory Usually does not store individual object data. Stores actual values for properties.
    Usage Used to create objects. Used to perform actual operations.

    Class vs Structure

    Some programming languages provide both classes and structures. The exact difference depends on the programming language. In general, a class is more commonly used for object-oriented programming because it supports advanced features such as methods, constructors, encapsulation, inheritance, and polymorphism.

    Feature Class Structure
    Purpose Used to model objects with data and behavior. Often used to group related data.
    Methods Commonly supports methods. May or may not support methods depending on language.
    OOP Features Supports core OOP concepts in many languages. Support depends on the language.
    Usage Used for complex entities and behavior. Used for simpler grouped data in many cases.

    How to Design a Class

    Designing a class means deciding what data and behavior should be grouped together. Before writing code, it is useful to analyze the problem carefully.

    Steps to Design a Class

    • Read the problem statement carefully.
    • Identify important nouns from the problem.
    • Select nouns that represent real entities or concepts.
    • Convert those entities into possible class names.
    • Identify data that each class should store.
    • Identify actions that each class should perform.
    • Decide which data should be public or private.
    • Write methods to operate on the class data.
    • Create objects from the class and test their behavior.
    CLASS DESIGN RULE
    Nouns become Classes   |   Verbs become Methods

    Example: Designing Classes from a School System

    Suppose we are building a school management system. The system needs to manage students, teachers, courses, exams, and results.

    From this requirement, we can identify the following classes:

    Class Possible Properties Possible Methods
    Student studentId, name, rollNumber, course attendClass(), submitAssignment(), viewResult()
    Teacher teacherId, name, subject takeClass(), assignMarks(), createExam()
    Course courseId, courseName, duration addStudent(), removeStudent(), displayCourse()
    Exam examId, examDate, subject scheduleExam(), cancelExam(), publishExam()
    Result studentId, marks, grade calculateGrade(), displayResult()

    This example shows how classes help divide a large system into smaller, manageable components.

    Common Mistakes Beginners Make with Classes

    While learning classes, beginners often make some common mistakes. Understanding these mistakes early helps improve class design.

    Common Mistakes

    • Confusing class with object.
    • Creating classes without clear purpose.
    • Putting all program logic inside one class.
    • Creating too many unnecessary classes.
    • Using unclear class names.
    • Making all data public without control.
    • Writing methods that perform too many tasks.
    • Ignoring constructor and initialization.

    Better Approach

    • Remember that class is a blueprint.
    • Create classes for meaningful entities.
    • Keep each class focused on one responsibility.
    • Use clear and descriptive class names.
    • Protect important data using access control.
    • Keep methods short and meaningful.
    • Initialize objects properly.
    • Design before writing code.

    Advantages of Using Classes

    Classes provide many advantages in software development. They make programs easier to design, understand, reuse, and maintain.

    Benefits of Classes

    • Classes organize related data and behavior together.
    • Classes make code modular and easier to manage.
    • Classes allow creation of multiple objects from one blueprint.
    • Classes improve code reusability.
    • Classes support encapsulation and data protection.
    • Classes help model real-world entities naturally.
    • Classes make large applications easier to maintain.
    • Classes support team-based software development.
    • Classes make testing and debugging easier.
    • Classes support advanced OOP features such as inheritance and polymorphism.

    Limitations of Classes

    Classes are powerful, but they should be used carefully. Not every simple problem requires complex class design.

    Overengineering Creating too many classes for a very small program can make the program unnecessarily complex.
    Design Complexity Poorly designed classes can make the application harder to understand and maintain.
    Learning Curve Beginners may need time to understand class, object, constructor, method, and access modifiers properly.
    Memory Consideration Creating many objects from classes may require more memory depending on the language and program design.

    Mini Practice Activity

    Try to identify possible classes, properties, and methods from the following scenarios. This activity will help you think like an object-oriented programmer.

    Scenario Possible Class Possible Properties Possible Methods
    Library Management Book title, author, isbn, availability borrowBook(), returnBook(), displayBook()
    Online Shopping Product productId, name, price, stock addToCart(), updateStock(), applyDiscount()
    Banking System Account accountNumber, holderName, balance deposit(), withdraw(), checkBalance()
    Hospital System Patient patientId, name, age, disease bookAppointment(), viewReport(), payBill()
    Transport System Vehicle vehicleNumber, type, speed, fuelLevel start(), stop(), accelerate(), refuel()

    Frequently Asked Questions

    1. What is a class in simple words?

    A class is a blueprint or template used to create objects. It defines what data an object will store and what actions it can perform.

    2. Is a class the same as an object?

    No. A class is a blueprint, while an object is an actual instance created from that blueprint. For example, Student is a class, and student1 is an object.

    3. Can one class create many objects?

    Yes. One class can be used to create many objects. Each object follows the same structure but stores different data.

    4. What does a class contain?

    A class can contain properties, methods, constructors, and access modifiers. It may also contain other features depending on the programming language.

    5. Why are classes important in OOP?

    Classes are important because they help organize code, support reusability, protect data, and represent real-world entities in software.

    6. Should every program use classes?

    Not necessarily. Very small programs may not need classes. However, classes are very useful for medium and large applications where code organization and reusability are important.

    Summary

    A class is one of the most important building blocks of Object-Oriented Programming. It acts as a blueprint for creating objects. It defines the properties and methods that objects will have.

    Classes help organize related data and behavior together. They make programs easier to understand, maintain, reuse, and expand. A well-designed class represents one clear entity or concept and contains only the data and behavior related to that entity.

    To understand classes properly, beginners should remember the relationship between class and object: a class is the design, and an object is the actual item created from that design.

    Key Takeaway

    A class is a blueprint or template in Object-Oriented Programming. It defines the properties and methods that objects will have. Classes make programs more organized, reusable, secure, and easier to maintain.