1. Gyanastra
  2. Programming Languages
  3. Object Oriented Concepts
  4. Classes Objects and Encapsulation
Free lesson, no account needed 11 min read 24 practice questions after it
Asked in past papers9 times
  • ISRO2017
  • UGC NET20172016201420132012200920072005

Programming Languages · Object Oriented Concepts

Classes Objects and Encapsulation

Overview

This lesson covers the basic object-oriented building blocks: a class as a blueprint, an object as an instance, and encapsulation as the mechanism that bundles data with the methods that operate on that data.
UGC NET treats this as part of Object Oriented Concepts and asks direct definitions, access-control rules, constructor facts, static versus instance members, class relationships, and short code traces.
Before studying it, a student should know basic variables, functions, and the idea of a user-defined data type.
The language conventions used here are C++ and Java because UGC questions mostly use these two; where they differ, the difference is stated explicitly.

Key concepts

  • A class is a user-defined type that groups data members and member functions. It is a blueprint, not an object.
  • An object is a run-time instance of a class. It has state stored in data members, behaviour provided by methods, and identity that distinguishes it from other objects even if their states are equal.
  • Encapsulation is the mechanism that binds code and data together into a single unit and protects the internal state from uncontrolled outside access. In OOP, the class is that unit.
  • Data hiding means restricting direct access to internal data. It is mainly achieved by private access. Encapsulation is broader: bundling plus controlled access.
  • Abstraction focuses on what an object does and hides unnecessary implementation detail. Encapsulation focuses on bundling and protecting implementation. Do not interchange the two.
  • Inheritance creates a new class from an existing class and models an is-a relationship.
  • Polymorphism allows similar operations to be used for similar purposes across different types. Overloading is compile-time polymorphism. Overriding is run-time polymorphism through inheritance.
  • Message passing means one object requests another object to perform an operation by invoking a method, usually with arguments and possibly a return value.
  • An Abstract Data Type (ADT) is a data type defined by its values and operations while hiding its representation. A class is a common implementation of an ADT.
  • Access specifiers in C++ are private, protected, and public. In C++, members of a class declared without any specifier are private; members of a struct are public by default. In Java, the default access is package-private, not private.
  • private members are accessible inside the class and, in C++, to friend functions or friend classes. protected members are accessible to the class, its friends, and derived classes under the usual language rules. public members are accessible from anywhere the object is visible.
  • A constructor has the same name as its class, has no return type, and initializes an object. A class can have any number of constructors provided their parameter lists differ. This is constructor overloading.
  • If no constructor is declared, the compiler supplies a default constructor in the usual C++/Java sense.
    A private constructor prevents direct instantiation from outside the class and is used for patterns such as singleton or utility classes.
  • A copy constructor creates a new object from an existing object of the same class. If it is not defined, C++ supplies one that copies members.
  • A destructor has no parameters, no return type, and is called automatically when an object’s lifetime ends. A class has one destructor.
  • A static data member is shared by all objects of the class. A static member function has no this pointer and cannot directly use non-static members.
  • A const member function in C++ promises not to modify the object’s non-mutable data and can be called on a const object.
  • A friend function is not a member of the class but is allowed to access private and protected members when declared as a friend inside the class.
  • Getter and setter methods provide controlled read and write access to private data. A setter can validate before changing state.
  • In Java, this refers to the current object inside an instance method. In C++, this is a pointer to the current object.
  • Aggregation is a weak part-whole relationship; the part can exist independently. Composition is strong ownership; the part normally dies with the whole.
  • Smalltalk is a pure object-oriented language: every value is an object, computation is by message sending, and classes and metadata are available and modifiable at run time. C++ and Java are hybrid object-oriented languages.
  • Java nested classes are of four standard kinds: static nested class, inner class, local class, and anonymous class.

How it works

  1. A class is written as a type definition. Its data members store state; its member functions define permitted operations. The class decides which members are public and which are hidden.
  2. An object is created by allocating storage and running a constructor. The constructor establishes a valid initial state.
  3. Outside code uses public operations, not private data. If a data member is private, code such as a.balance = 900; is rejected unless it is inside the class or inside a friend.
  4. Encapsulation works by combining the data and the methods in one class and exposing only a controlled interface. Data hiding is the restrictive part; encapsulation is the whole arrangement.
  5. Static members belong to the class, not to an individual object. All objects share static data, while each object gets its own copy of non-static data.
  6. Constructors may be overloaded because the compiler distinguishes them by the number, types, and order of parameters. Return type alone cannot distinguish overloads.
  7. When a subclass method has the same name and type signature as a superclass method, it overrides it. When methods share a name but have different parameter lists, they overload each other.
Figure. Notice that balance is private while deposit and getBalance are public, so access is controlled. Encapsulation is the whole arrangement, with data hiding as its restrictive part.

Worked examples

Example 1: Match the OOP term with its meaning.
List-I: A. Encapsulation, B. Abstraction, C. Inheritance, D. Polymorphism.
List-II: i. Bundling data and methods into one unit; ii. Showing only essential behaviour and hiding implementation detail; iii. Creating a new class from an existing class; iv. Using similar operations for similar purposes across types.
Matching: A-i, B-ii, C-iii, D-iv. Encapsulation is the bundle plus controlled access; abstraction is the selective view; inheritance is the is-a relation; polymorphism is the many-forms behaviour.

Example 2: Access control in C++.

#include <iostream>
using namespace std;

class Account {
private:
    int balance;
public:
    Account(int b) : balance(b) {}
    void deposit(int x) {
        if (x > 0) balance += x;
    }
    int getBalance() const { return balance; }
};

int main() {
    Account a(500);
    a.deposit(200);
    // a.balance = 900; // compile error: balance is private
    cout << a.getBalance();
    return 0;
}

Output:

700

Ramesh’s account starts with 500 rupees. The public deposit method adds 200 only after checking that the amount is positive. The private member cannot be changed directly from main, which is data hiding through encapsulation.

Example 3: Number of constructors.

class Box {
public:
    Box() {}
    Box(int x) {}
    Box(int x, int y) {}
};

This class has three constructors. A class may have any number of constructors as long as their parameter lists are distinct. If no constructor were written, the compiler would provide a default constructor in the usual sense.

Example 4: Static member count.

#include <iostream>
using namespace std;

class Counter {
private:
    static int count;
public:
    Counter() { ++count; }
    static int getCount() { return count; }
};

int Counter::count = 0;

int main() {
    Counter a, b, c, d, e, f, g;
    cout << Counter::getCount();
    return 0;
}

Output:

7

Seven objects are created, and each constructor increments the same shared static member count. Non-static data would have given seven separate copies, but static data is one copy for the whole class.

Example 5: Two-step static and destructor trace.

#include <iostream>
using namespace std;

class Track {
private:
    static int created;
    static int alive;
public:
    Track() { ++created; ++alive; }
    ~Track() { --alive; }
    static int getCreated() { return created; }
    static int getAlive() { return alive; }
};

int Track::created = 0;
int Track::alive = 0;

int main() {
    Track a, b;
    {
        Track c, d, e;
    }
    cout << Track::getCreated() << " " << Track::getAlive();
    return 0;
}

Output:

5 2

Five objects are created in total: a, b, c, d, e, so created is 5. The inner block ends, so c, d, e are destroyed and alive falls from 5 to 2. Objects a and b are still alive when the output is printed.

Comparison

TermPrecise meaningCommon trap
EncapsulationBundles data and methods into one class and controls accessIt is not merely “hiding implementation detail”; that is closer to abstraction
Data hidingPrevents direct access to internal data, usually by privateData hiding is one part of encapsulation, not the whole of OOP
AbstractionExposes essential behaviour, hides unnecessary detailAbstraction asks “what”; encapsulation protects “how”
InheritanceIs-a relationship; new class reuses/extends anotherIt is a relationship, not a module or test technique
PolymorphismSame interface, different behaviourOverloading and overriding are different mechanisms
AccessC++ class defaultC++ struct defaultJava defaultWho can access
privateYesNoNoClass and friends in C++
protectedNoNoNoClass, friends, derived classes under language rules
publicNoYesNoAny visible code
default/packageprivate in C++ classpublic in C++ structpackage-private in JavaSame package in Java; not private
RelationMeaningExample
AssociationGeneral relationship between objectsTeacher teaches Student
AggregationWeak part-whole; part can exist independentlyDepartment has Teachers
CompositionStrong part-whole; part owned by wholeHouse owns Rooms
InheritanceIs-a relationshipCar is-a Vehicle
OverloadingOverriding
Same method name, different parameter listSame method name and same type signature in subclass
Compile-time polymorphismRun-time polymorphism
Return type alone cannot distinguish overloadsSubclass method replaces superclass method for the object

Revision summary

  • Encapsulation = bundle data and methods; data hiding = restrict direct access.
  • private is the default for C++ class members; Java default is package-private.
  • A constructor has the same name as the class and no return type.
  • Any number of constructors are allowed if parameter lists differ.
  • Static data is shared; non-static data is separate per object.
  • A friend is not a member but can access private members.
  • Composition is strong ownership; aggregation is weak part-whole.
  • Abstraction asks what; encapsulation protects how.
  • Overloading is compile-time; overriding is run-time.
  • ADT = data values plus operations, with representation hidden.
  • Message passing = one object invokes another object’s method.

Previous-year exam insights

  • Direct definition questions ask for “binding code and data” or “data hiding”; the answer is usually encapsulation, not abstraction.
  • Match-the-list questions mix encapsulation, abstraction, inheritance, and polymorphism.
    Read “bundling data and methods” as encapsulation and “essential behaviour only” as abstraction.
  • Statement I/II questions often swap abstraction and encapsulation.
    Encapsulation does not mean “ignoring irrelevant detail”; that is abstraction.
  • Access-control questions test C++ default private, Java package-private, and the C++ friend exception.
    Private does not mean inaccessible to friend functions.
  • Constructor questions test “any number with distinct signatures”, no return type, default constructor supply, and private constructors preventing outside instantiation.
  • Code/numeric questions test static data shared by all objects and destructors decrementing counts.
    Separate static counters from instance counters before computing.
  • Relationship questions test composition as strong full ownership and aggregation as weak part-whole.
    Association is the general term.
  • Overloading-versus-overriding is a common trap: same name with different parameters is overloading; same signature in subclass is overriding.

Practice at PARIKSHA

You are ready for the PARIKSHA tests of this sub-topic when you can:

  • Define class, object, encapsulation, data hiding, abstraction, inheritance, polymorphism, and message passing without mixing them.
  • Choose the correct access specifier in C++ and Java and explain the default access in each language.
  • Count constructors in a class and decide whether a default or private constructor is available.
  • Trace static data and alive-object counts through object creation and destruction.
  • Distinguish aggregation, composition, association, and inheritance from short descriptions.
  • Distinguish overloading from overriding by signature and binding time.
  • Explain getter, setter, friend function, const member function, and static member function in one line each.
  • Evaluate assertion-and-reason or Statement I/II items on encapsulation and data hiding.
  • Explain how an ADT is implemented by a class with hidden representation and public operations.

Attempt the sub-topic test first; after clearing it, move to the subject test.

Pages 1–2 of 2