Object-oriented programming builds software from objects — bundles of data plus the functions that act on it. Abstraction, encapsulation, inheritance, polymorphism, message passing and dynamic binding are the vocabulary behind nearly every C++ and Java question.
Think of a car. You drive it through a small interface — steering, pedals, gear lever — without knowing how fuel injection works: that is abstraction. The engine is sealed under the bonnet so you cannot fiddle with it directly: that is encapsulation. An electric car is still a car, plus a battery: inheritance. Pressing 'start' does different things in a petrol car and an electric one, yet the button is the same: polymorphism. The car's design drawing is the class; every real car on the road is an object.
Key points — the night-before list
Class = blueprint / user-defined type; object = a run-time instance with state (data), behaviour (methods) and identity (its own memory).
Abstraction shows only essential features and hides how they work (the what, not the how) — built with abstract classes, interfaces and ADTs.
Encapsulation wraps data and functions into one unit (the class); data hiding makes fields private so only the class's own methods can touch them.
Four pillars: abstraction, encapsulation, inheritance, polymorphism. Balagurusamy's feature list adds objects, classes, dynamic binding and message passing.
Message passing: obj.method(args) names the receiving object, the message (method) and the information (arguments).
Dynamic (late) binding picks the method body at run time from the object's actual type — virtual functions in C++, every overridable method in Java.
C++ access: private (class default), protected, public (struct default). Java adds package-private (no keyword): visible inside the same package only.
OOP is bottom-up and data-centred; procedural programming (C, Pascal, FORTRAN) is top-down and function-centred, with data shared through globals.
01From procedures to objects
In procedure-oriented programming (POP) a program is a sequence of instructions grouped into functions. C, Pascal and FORTRAN work this way: you split the problem into steps (top-down decomposition), write one function per step, and let the functions share data — very often through global variables.
That is fine for small programs. As a program grows, one global variable may be read and modified by dozens of functions. Change its format and every one of those functions must change; any of them can corrupt it by accident. The data and the code that is supposed to look after it live far apart.
Object-oriented programming (OOP) turns this around. You first ask which things exist in the problem — accounts, customers, loans, housing units — and model each as an object that keeps its own data and offers operations on it. The program is then assembled bottom-up from such objects, which cooperate by calling one another's operations.
CProcedural style in C — the data and the functions that change it are separate
POP emphasises doing things (algorithms) and follows the top-down approach; OOP emphasises data and follows the bottom-up approach. 'Data moves openly around the system from function to function' is the classic description of POP.
02Classes, objects and message passing
A class is a user-defined data type. It describes what its objects will hold — data members (also called fields, attributes or instance variables) — and what they can do — member functions (also called methods). A class is only a description: declaring it reserves no memory for any data.
An object is an instance of a class: a variable of that type, created at run time. Every object has state (the current values of its data members), behaviour (the methods it responds to) and identity (it is a distinct thing in memory, even when its state equals another object's). Creating an object is called instantiation.
C++C++ — a class with hidden data and a public interface (prints: Anu 6500 0)
#include <iostream>#include <string>
using namespace std;
class Account {
private: // hidden data: only member functions can touch it
string owner;
double balance;
public: // the public interface
Account(string name, double opening) : owner(name), balance(0) {
deposit(opening);
}
bool deposit(double amt) {
if (amt <= 0) return false; // validation protects the data
balance += amt;
return true;
}
bool withdraw(double amt) {
if (amt <= 0 || amt > balance) return false;
balance -= amt;
return true;
}
double getBalance() const { return balance; }
string getOwner() const { return owner; }
};
int main() {
Account a("Anu", 5000);
a.deposit(1500); // message "deposit 1500" sent to object a
bool ok = a.withdraw(10000); // refused: more than the balance
cout << a.getOwner() << " " << a.getBalance() << " " << ok << endl;
// a.balance = 1e9; // compile error: 'balance' is private
return 0;
}
JavaJava — the same design (prints: Anu 6500.0 false)
public class Account {
private String owner; // hidden data
private double balance;
public Account(String owner, double opening) {
this.owner = owner;
deposit(opening);
}
public boolean deposit(double amt) {
if (amt <= 0) return false;
balance += amt;
return true;
}
public boolean withdraw(double amt) {
if (amt <= 0 || amt > balance) return false;
balance -= amt;
return true;
}
public double getBalance() { return balance; }
public String getOwner() { return owner; }
public static void main(String[] args) {
Account a = new Account("Anu", 5000); // the object lives on the heap; a holds a reference
a.deposit(1500);
boolean ok = a.withdraw(10000);
System.out.println(a.getOwner() + " " + a.getBalance() + " " + ok);
}
}
Objects cooperate by message passing. The call a.deposit(1500) sends the message deposit to the object a, carrying the information 1500; the object decides how to respond by running its own method. A message therefore names three things: the receiving object, the method and the arguments.
Notice the small language differences. The C++ class ends with a semicolon after its closing brace, and an object can be an ordinary local variable (Account a(...)). Java keeps every object on the heap — normally created with new — and the variable a holds only a reference to it. C++ prints the bool as 0 and the double as 6500; Java prints false and 6500.0.
Memory aid
Every object has S-B-I: State, Behaviour, Identity. The class is the cookie-cutter; objects are the cookies.
Interactive · Inheritance & dispatch explorer Full page
Loading interactive tool…
03Abstraction: expose the what, hide the how
Abstraction means representing the essential features of something while leaving out the background details. A user of a class should need to know what it does — its operations and what they mean — and never how it does them.
There are two flavours. Procedural (control) abstraction: a call such as sqrt(x) hides an algorithm behind a name. Data abstraction: a type such as a stack is known only by its operations — push, pop, isEmpty — while the array or linked list underneath stays invisible. A type defined purely by its operations is an abstract data type (ADT), and classes are how OOP languages build ADTs.
C++C++ — the abstraction (IntStack) is separate from one implementation (ArrayStack); prints 3 2 1
#include <iostream>
using namespace std;
class IntStack { // abstract class: no objects of this type
public:
virtual void push(int x) = 0; // pure virtual = "every stack must provide this"
virtual int pop() = 0;
virtual bool isEmpty() const = 0;
virtual ~IntStack() {}
};
class ArrayStack : public IntStack { // one possible HOW, hidden from users
int data[100];
int top = -1;
public:
void push(int x) override { data[++top] = x; }
int pop() override { return data[top--]; }
bool isEmpty() const override { return top == -1; }
};
void reverseThree(IntStack& s) { // client code sees only the abstraction
s.push(1); s.push(2); s.push(3);
while (!s.isEmpty()) cout << s.pop() << " ";
cout << "\n";
}
int main() {
ArrayStack st;
reverseThree(st);
}
JavaJava — this interface is a pure abstraction (abstract methods only); any class can implement it
interface IntStack { // WHAT a stack offers
void push(int x);
int pop();
boolean isEmpty();
}
class ArrayIntStack implements IntStack { // one HOW; a linked version could replace it
private int[] data = new int[100];
private int top = -1;
public void push(int x) { data[++top] = x; }
public int pop() { return data[top--]; }
public boolean isEmpty() { return top == -1; }
}
Because reverseThree depends only on IntStack, you can swap ArrayStack for a linked-list stack tomorrow and the client code will not change. That freedom is the practical pay-off of abstraction.
Abstract classes and pure virtual functions (C++) — declare operations without bodies.
Abstract classes and interfaces (Java) — a contract that implementing classes must honour.
Header vs implementation files (C++) — users read account.h; the details live in account.cpp.
Access specifiers — helper functions and internal fields are kept private, out of sight.
Note
Abstraction is decided at design time — what should the outside world see? Encapsulation is the implementation mechanism that enforces that decision.
04Encapsulation and data hiding
Encapsulation is the wrapping up of data and the functions that operate on it into a single unit — the class. Because the data lives with its functions, the class can protect it: fields are made private, and the outside world reaches them only through public methods. Keeping data away from direct outside access is called data hiding (or information hiding).
Why bother? A class that guards its fields can enforce invariants — rules that must always hold, such as balance never negative or age between 18 and 60. It can also change its internal representation later (store paise instead of rupees, say) without breaking a single caller, because callers only ever saw the methods.
JavaGetters (accessors) and setters (mutators) that actually enforce rules
public class Employee {
private String name;
private int age;
public String getName() { return name; } // getter (accessor)
public void setName(String name) { // setter (mutator)
if (name == null || name.trim().isEmpty())
throw new IllegalArgumentException("name required");
this.name = name;
}
public int getAge() { return age; }
public void setAge(int age) {
if (age < 18 || age > 60) // the business rule lives in ONE place
throw new IllegalArgumentException("age must be 18-60");
this.age = age;
}
}
C++ specifier
Same class
Derived class
Anywhere else
private
Yes
No
No
protected
Yes
Yes
No
public
Yes
Yes
Yes
C++ access specifiers (friend functions and friend classes can also reach private and protected members)
Java modifier
Same class
Same package
Subclass in another package
Any other class
private
Yes
No
No
No
(none) package-private
Yes
Yes
No
No
protected
Yes
Yes
Yes (through inheritance)
No
public
Yes
Yes
Yes
Yes
Java access modifiers
Abstraction
Hides complexity — the implementation details
Design level: decides what to show
Focus: what an object does
Built with abstract classes, interfaces, ADTs
Example: a TV remote shows only buttons
Encapsulation
Hides data and binds it to its methods
Implementation level: keeps the data safe
Focus: how the data is protected
Built with classes plus private / protected / public
Example: the circuit board sealed inside the remote's case
Common mistake
A getter and a setter for every field is not automatically encapsulation. If a setter accepts any value, the field is effectively public. Real encapsulation puts the rules — validation and consistency — inside the class.
05Inheritance, polymorphism and dynamic binding
Inheritance lets a new class (derived class / subclass) acquire the members of an existing class (base class / superclass) and add or refine its own. It models an is-a relationship — a savings account is an account — and gives code reuse plus a natural hierarchy of classification. (Full treatment in the Inheritance topic.)
Polymorphism (Greek: many forms) means one name or interface can stand for different behaviours. Compile-time polymorphism comes from function and operator overloading — the compiler picks a version from the argument types. Run-time polymorphism comes from overriding — a base-class pointer or reference can refer to objects of different subclasses, and each object answers the same call in its own way.
Binding connects a call to the code that runs. With static (early) binding the compiler fixes it from the declared type. With dynamic (late) binding the choice waits until run time and uses the object's actual type. C++ gives dynamic binding only to virtual functions called through a pointer or reference; in Java every non-static, non-private, non-final method is bound dynamically.
C++One message, three behaviours — dynamic binding in action (prints: 0 3.5 7.1)
#include <iostream>
using namespace std;
class Account {
public:
virtual double interestRate() const { return 0.0; } // virtual: bound at run time
virtual ~Account() {}
};
class Savings : public Account { // Savings IS-A Account
public:
double interestRate() const override { return 3.5; }
};
class FixedDeposit : public Account {
public:
double interestRate() const override { return 7.1; }
};
int main() {
Account* list[] = { new Account, new Savings, new FixedDeposit };
for (Account* a : list)
cout << a->interestRate() << " "; // the pointer type is always Account*
cout << "\n";
for (Account* a : list) delete a;
}
Tip
Try it in the Inheritance & dispatch explorer on this page: toggle virtual on and off and watch which method runs for the same pointer.
06Benefits, limits and the OOP family tree
Reusability — inherit or compose existing, tested classes instead of rewriting them.
Data security — data hiding stops accidental or unauthorised changes.
Modularity — each class is a self-contained unit that can be built, tested and replaced on its own.
Maintainability and extensibility — new behaviour is often just a new subclass, leaving old code untouched.
Real-world mapping — classes mirror the nouns of the problem, so designs are easy to discuss with users.
Team work and scale — clear class interfaces let many programmers work in parallel on large systems.
Polymorphism — client code such as draw every shape keeps working when new types are added.
OOP has costs too: programs can be larger and slightly slower (object overhead, indirect virtual calls), good class design takes experience, and for a small, purely computational task a few plain functions are simpler.
Language
Year
Creator(s)
Why it matters
Simula 67
1967
Ole-Johan Dahl and Kristen Nygaard (Norway)
First OO language: classes, objects, inheritance
Smalltalk
1972–80
Alan Kay and team, Xerox PARC
Pure OO — everything is an object; Kay coined the term object-oriented
C++
1979 (named C++ in 1983)
Bjarne Stroustrup, AT&T Bell Labs
Began as C with Classes; a hybrid, multi-paradigm language
Java
1995
James Gosling, Sun Microsystems
Class-based, runs on the JVM; not pure OO because of primitive types
Landmark object-oriented languages
Object-based languages support objects and encapsulation but not inheritance (hence no dynamic binding through it) — Ada 83 and classic Visual Basic are the usual textbook examples. In short, object-oriented = object-based + inheritance + dynamic binding. A pure OO language (Smalltalk) treats everything, even numbers, as objects; C++ is a hybrid, and Java is nearly pure but keeps eight primitive types.
PSC favourite
Frequently asked: first OOP language → Simula 67; C++ developed by → Bjarne Stroustrup at Bell Labs (1979, named C++ in 1983); object-based languages lack → inheritance; pure OO language → Smalltalk.
07Modelling a real-world problem in classes
OOP design starts with the problem statement, not with code. The recipe below is the one used in textbooks (and in industry, in lighter form) to turn a description into classes.
From requirements to classes
Find the nouns
Each important, independent thing in the description is a candidate class (Applicant, Scheme, HousingUnit). Nouns that merely describe another thing become attributes (income limit).
List attributes
Decide what each class must remember. Make every attribute private by default.
Find the verbs
Actions become methods, placed on the class that owns the data they use (a scheme checks eligibility, so isEligible() belongs to Scheme).
Decide relationships
Is-a → inheritance (a LowIncomeScheme is a Scheme). Has-a → composition (a Scheme has HousingUnits). Uses → a method parameter.
Choose visibility
Expose the smallest public interface that lets clients do their job; keep helpers and fields private.
Mark variation points
Where behaviour differs by type, declare it once in the base class (virtual / overridable) and override it in subclasses — polymorphism.
JavaA skeleton that applies every step (details are filled in Worked example 1)
class Applicant {
private final String id;
private final String name;
private final double annualIncome;
Applicant(String id, String name, double annualIncome) {
this.id = id; this.name = name; this.annualIncome = annualIncome;
}
double getAnnualIncome() { return annualIncome; }
String getName() { return name; }
}
abstract class Scheme {
private final String code;
protected final java.util.List<HousingUnit> units = new java.util.ArrayList<>(); // has-a
Scheme(String code) { this.code = code; }
abstract boolean isEligible(Applicant a); // variation point
long availableUnits() { return units.stream().filter(u -> !u.isAllotted()).count(); }
}
class LowIncomeScheme extends Scheme { // is-a
LowIncomeScheme(String code) { super(code); }
boolean isEligible(Applicant a) { return a.getAnnualIncome() <= 300000; }
}
class HousingUnit {
private final String unitNo;
private boolean allotted;
HousingUnit(String unitNo) { this.unitNo = unitNo; }
boolean isAllotted() { return allotted; }
void markAllotted() { // the only way to change 'allotted'
if (allotted) throw new IllegalStateException(unitNo + " already allotted");
allotted = true;
}
}
Tip
A good class has high cohesion (its members belong together) and low coupling (it depends on few other classes, and only through their public interfaces). Both follow naturally from abstraction and encapsulation.
Worked examples
Try the problem first, then reveal the working one step at a time.
EX 1Design: the housing-allotment system
The Housing Board wants software in which applicants apply for houses under schemes. Each scheme has a number of housing units and an income limit; an allotment links one applicant to one unit. Identify classes, attributes, methods and relationships, and show where abstraction, encapsulation, inheritance and polymorphism appear.
EX 2Spot the OOP concept
Name the concept in each statement: (a) an ATM screen offers Withdraw, Deposit and Balance but never shows the bank's database; (b) balance is private and changes only inside deposit() and withdraw(); (c) class CurrentAccount extends Account; (d) shape.area() returns πr² for a circle and l × b for a rectangle; (e) acct.transfer(other, 500); (f) which area() runs is decided only when the program runs.
EX 3Predict the result: struct vs class
Given struct P { int x; }; and class Q { int x; public: void set(int v) { x = v; } int get() { return x; } };, main contains line A P p; p.x = 10;, line B Q q; q.set(20);, line C q.x = 30; and finally cout << p.x + q.get();. Which lines compile, and what is printed?
Practice session
Work each problem on paper first, then check. Marking one solved earns 10 XP.0/5 solved
Q1
Using a mobile phone, give one example of abstraction and one of encapsulation, and explain in two lines why they are different ideas.
Q2
Package bank has public class Account { double balance; protected String branch; }. In package app, public class Main (which does not extend Account) runs Account a = new Account(); a.balance = 100; a.branch = "Kochi";. Which assignments compile? What changes if Main extends Account?
Q3
Rewrite this procedural C fragment as a class in C++ and in Java so that the count can never become negative: int count = 0; void inc() { count++; } void dec() { count--; } int get() { return count; }
Q4
True or false? (i) An object-based language supports inheritance. (ii) In C++, struct members are public by default. (iii) Data hiding is achieved by declaring members public. (iv) Dynamic binding is resolved at compile time. (v) A message to an object specifies the object, the method and the arguments.
Q5
Design a Java class Temperature that stores a value in Celsius, lets callers read it in Celsius or Fahrenheit, and refuses any value below absolute zero (−273.15 °C).
Exam traps
Abstraction ≠ encapsulation. Abstraction decides what to expose (design); encapsulation bundles data with methods and hides the rest (implementation). Data hiding is the result of encapsulation with private.
In C++ the only differences between class and struct are the default member access (private vs public) and the default inheritance mode. Java has no struct at all.
Java's no-modifier access is package-private — not public, not private. Java's protected is wider than C++'s because it also opens the member to the whole package.
Books count OOP 'features' differently: four pillars, or Balagurusamy's eight (objects, classes, abstraction & encapsulation, inheritance, polymorphism, dynamic binding, message passing). For 'which is NOT an OOP feature', look for top-down design, global data or procedures.
Dynamic binding (choosing a method body at run time) has nothing to do with dynamic memory allocation (new, malloc).
Java is not a 'pure' OO language (primitives like int are not objects), and C++ is a hybrid — a C++ program need not contain a single class.
Quiz — KPSC style
12 questions. 70 % passes the topic quiz (+30 XP, +20 more for 100 %). Exam scoring: +1 correct, −⅓ wrong.