0% found this document useful (0 votes)
3 views35 pages

Oops Notes

The document is a comprehensive guide on Object Oriented Programming (OOP), covering fundamental concepts such as classes, objects, encapsulation, inheritance, polymorphism, and abstraction. It includes detailed explanations, code implementations in C++ and Java, and discusses access specifiers, constructors, destructors, and the differences between shallow and deep copies. The document also features a structured index and multiple-choice questions with answers to reinforce learning.

Uploaded by

sanikagad1
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views35 pages

Oops Notes

The document is a comprehensive guide on Object Oriented Programming (OOP), covering fundamental concepts such as classes, objects, encapsulation, inheritance, polymorphism, and abstraction. It includes detailed explanations, code implementations in C++ and Java, and discusses access specifiers, constructors, destructors, and the differences between shallow and deep copies. The document also features a structured index and multiple-choice questions with answers to reinforce learning.

Uploaded by

sanikagad1
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

abhishekshinde5805@gmail.

com
Object Oriented
Programming System

1
INDEX

abhishekshinde5805@[Link]
[Link] TOPIC PAGE NO.
Object Oriented Programming System 1 – 35
1 Introduction 3
2 Classes & Objects 4
3 Code Implementation (classes & Objects) 5
4 Access Specifiers / Modifiers 6
5 Friend Class 7
6 Core Concept of OOPs 8
7 Encapsulation 9
8 Constructor 10
9 Destructor 11
10 Scope Resolution Operator (::) 12
11 This Pointer 13
12 Shallow and Deep Copy 14 – 15
13 Inheritance 16
14 Modes of Inheritance 16
15 Types of Inheritance 17 – 19
16 The Diamond Problem 20 – 21
17 Polymorphism 22
18 Compile-time Polymorphism (Static Binding) 22 – 23
19 Run-time Polymorphism (Dynamic Binding) 24 – 25
20 Virtual Functions 25
21 Abstraction 26
22 Abstract Classes and Pure Virtual Functions (C++) 26 – 27
23 Abstract Class in Java / Interface in Java 27 – 28
24 Static Data Member and Function 29
25 MCQs 30 – 33
26 Answer Key and Explanation 34 – 35

Important topics

2
Introduction

abhishekshinde5805@[Link]
What is OOPs
It's a programming paradigm based on the concept of "objects," which contain both data
(fields or attributes) and code (methods or procedures) to manipulate that data.
Or
“OOP is a programming paradigm that revolves around the concepts of objects and classes.
Or
OOP is about designing software using real-world entities like Car, Student, Account, etc.,
which have properties and behaviors.

Need of OOPs

Problem in Procedural Code OOPs as a Solution

No clear modular structure Classes group data & logic

Poor code reuse Inheritance enables reuse

Data is not secure Encapsulation hides sensitive info

Difficult to manage large code OOPs offers abstraction & structure

Hard to model real-world entities OOPs models real-world objects

*Procedural Programming: Code is written as a sequence of instructions.

Advantages of OOPs
• Modularity: Code is divided into classes and objects, making it organized and
manageable.
• Reusability: Inheritance allows us to reuse existing code, reducing redundancy.
• Data Hiding (Security): Encapsulation hides internal object details, exposing only what's
necessary.
• Maintainability: Code is easier to update or extend without affecting unrelated parts.
• Real-world Modelling: Mirrors real-world entities like Student, Car, etc.
• Scalability: Complex and large-scale applications can be designed and maintained
efficiently.

3
Classes & Objects

abhishekshinde5805@[Link]
Class
Class is the blueprint / template that defines the structure and behavior (data and functions)
of objects.

Objects
● Objects are real world entities / instances of class.
● It contains some characteristics (attributes / properties / variables) & behaviors
(methods) specified in the class template.

NOTE: Class is the blueprint that defines attributes and methods, while an object is a real
instance of that blueprint, created in memory and used to perform operations.

Example 1: Class of Pen and Object P

Example 2: Car

Real-world Concept OOPs Equivalent

Car Blueprint Class

Actual Car Object

Color, Engine Attributes (Data)

Drive, Brake Behaviors (Methods)

4
Code Implementation for Classes and Objects

abhishekshinde5805@[Link]
C++ Code

#include <iostream>
using namespace std;

class Car {
public:
string color;
int engineCC;

void drive() {
cout << "Driving a " << color << " car with " << engineCC << "cc engine." << endl;
}
};

int main() {
Car myCar; // Object created statically
[Link] = "Red";
[Link] = 2000;
[Link]();

Car* carPtr = new Car(); // Dynamic memory allocation


carPtr->color = "Blue";
carPtr->engineCC = 2200;
carPtr->drive();
}

Java Code

class Car {
private String color;
private int engineCC;

void drive() {
[Link]("Driving a " + color + " car with " + engineCC + "cc engine.");
}

public static void main(String[] args) {


Car myCar = new Car();
[Link] = "Red";
[Link] = 2000;
[Link]();
}
}

5
Access Specifiers / Modifiers

abhishekshinde5805@[Link]
Access specifiers / modifiers define the visibility or access level of class members
(variables & methods).

Types of Access specifiers / modifiers


1. Private: Attributes and Methods accessible inside a class.
2. Protected: Attributes and Methods accessible inside a class & by its derived class.
3. Public: Attributes and Methods accessible to everyone.

Access Modifier Class Package Sub Class World

Private ✔ ❌ ❌ ❌

Protected ✔ ✔ ✔ ❌

Public ✔ ✔ ✔ ✔

The above table applies to Java. In C++, only private, protected, and public exist.

6
Friend Class

abhishekshinde5805@[Link]
(Only in C++)
● A friend class in C++ is a class that is granted special access to the private and
protected members of another class.
● Even though the data is private/protected, a friend class can access it directly.

Real Life Example: Imagine your Car class has a private engine Number. You don’t want
anyone to access it. Except your Mechanic class, which needs access for service. So, you
make Mechanic a friend class of Car.

#include <iostream>
using namespace std;

class Car {
private:
string engineNumber;

public:
Car() {
engineNumber = "XYZ1234";
}

// Declare Mechanic as a friend class


friend class Mechanic;
};

class Mechanic {
public:
void checkEngine(Car c) {
cout << "Accessing engine number: " << [Link] << endl;
}
};

int main() {
Car myCar;
Mechanic m;
[Link](myCar); // Can access private member
return 0;
}

7
Core Concepts of OOPs

abhishekshinde5805@[Link]
The four pillars of OOP are:

Encapsulation
● Wrapping data (attributes / variables) and methods into a single unit called class.
● Ensures data hiding using private access modifiers.
Real life Example: A capsule hides the bitter medicine inside a protective shell, just like a
class hides its data and exposes it only through methods.

Inheritance
● One class / Child class / Derived class inherits properties and behavior from another class
/ parent class / base class.
● Promotes code reuse and hierarchical structure.
Real life Example: A child inherits traits like eye color and height from their parents.

Polymorphism
● Ability of objects to take on different forms or behave in different ways depending on
the context in which they are used.
● Types:
a. Compile-time / Static: Method Overloading.
b. Run-time / Dynamic: Method Overriding.
Real life Example: The same person acts as a student at college, a player on the field, and
a child at home - different roles, same individual.

Abstraction
● Hiding all the unnecessary details and showing only the relevant features.
● Achieved via pure virtual functions (C++) or abstract classes / interfaces (Java).
Real life Example: You use a smartphone by tapping icons, without knowing the internal code
behind apps.

8
Encapsulation

abhishekshinde5805@[Link]
● Wrapping data (attributes / variables) and methods into a
single unit called class and restricting direct access to the
internal data.
● Ensures data hiding using private access modifiers.
● Think of it as putting everything related to an object inside a
capsule (class).
Real life Example: A capsule hides the bitter medicine inside a protective shell, just like a
class hides its data and exposes it only through methods.

C++ Code Java Code

class Student { class Student {


private: private int age;
int age;
public void setAge(int a) {
public: if (a > 0) age = a;
void setAge(int a) { }
if (a > 0) age = a;
} public int getAge() {
return age;
int getAge() { }
return age;
} public static void main(String[] args) {
}; Student s = new Student();
//Encapsulated access
int main() { [Link](20);
Student s; // Output: 20
[Link](20); // Valid setter call [Link]([Link]());
cout << [Link](); // Output: 20 }
// [Link] = 25; ❌ Not allowed (private) }
}

9
Constructor

abhishekshinde5805@[Link]
● Special method which is invoked automatically (only called once) at the time of object
creation.
● Used for initialisation of an object.
● Has the same name as class & does not have a return type.
● Memory allocation of objects happens before the constructor call; the constructor is used
for initialization.

Types of Constructor
1. Non-Parameterised / Default
2. Parameterised
3. Copy Constructor

Non-Parameterised Parameterised Copy Constructor

● Having no parameters. ● Accepts parameters to ● Special constructor which


● Used when we want to create initialize object values at creates a new object as a copy
objects without passing any creation time. of an existing object.
values.

class Student { class Student { class Student {


public: public: public:
Student() { string name; string name;
cout << "Non- Student(string n) { Student(string n) {
Parameterised / Default name = n; name = n;
Constructor called\n"; } }
} };
}; // Copy Constructor
Student(const Student &s) {
name = [Link];
}
};

class Student1 { class Student2 { class Student3 {


Student1() { String name; String name;
[Link]("Non-
Parameterized Constructor Student2(String n) { Student3(String n) {
called"); name = n; name = n;
} } }
} }
// Copy Constructor
Student3(Student3 s) {
[Link] = [Link];
}
}

10
Destructor
(Only in C++)

abhishekshinde5805@[Link]
● A destructor is a special member function that is automatically called when an object
goes out of scope or is explicitly deleted.
● Used to free resources like memory, file handles, etc.
● Same as class name and prefixed with ~.
● Has no return type and parameter.

Example:

C++ Code

#include <iostream>
using namespace std;

class Student {
public:
Student() {
cout << "Constructor called\n";
}

~Student() {
cout << "Destructor called\n";
}
};

int main() {
Student s1; // Constructor called
} // Destructor automatically called at end of scope

What About Java?


Java doesn’t have destructors. Instead, it has a garbage collector.
Garbage Collector
● It is a memory management feature.
● Automatically frees memory occupied by objects no longer in use.
● Don’t need to manually delete objects in Java - the Garbage Collector does it.
Garbage Collection
● Process of automatically identifying and removing objects from memory that are no
longer used by a program.

Need of Garbage Collection


● Detects unreachable objects
● Reclaims their memory and Prevents memory leaks
● Keeps your app efficient and safe

NOTE: Destructor is used in C++ to clean up when the object is no longer needed. Java
does not need destructors because it uses automatic garbage collection.

11
Scope Resolution Operator (::)
(Only in C++)

abhishekshinde5805@[Link]
• Used to access members (variables or functions) that are outside the current scope or
belong to a specific class / namespace.

Use Cases

Access Global Variable when Local Variable Shadows it

int x = 10; // global

int main() {
int x = 20; // local
cout << x << endl; // prints 20
cout << ::x << endl; // prints global x = 10 using scope resolution
}

Define Class Functions Outside the Class

class Student {
public:
void show(); // function declared
};

void Student::show() { // defined using scope resolution


cout << "Student function defined outside the class." << endl;
}

Access Namespaces

namespace A {
int value = 5;
}

int main() {
cout << A::value; // Access value from namespace A
}

12
This Pointer

abhishekshinde5805@[Link]
• this keyword is a pointer (in C++) / reference (in Java) that refers to the current object -
the object whose method or constructor is being executed.
• Helps to differentiate between class attributes and parameters, especially when they
have the same name.
• Available only inside non-static member functions.
• Not available in static methods (no object context).

C++ Java

● Uses -> to access members directly, or *this ● Uses. (dot) to access members.
to dereference the pointer to the current
object, allowing member access via the dot
operator (.).

● Pointer (this ->) ● Reference (this.)

class Student { class Student {


public: String name;
string name;
Student(String name) {
Student(string name) { // referring to the current object's name
// referring to the current object's name [Link] = name;
this->name = name; }
}
void show() {
void show() { [Link]("Name: " + [Link]);
cout << "Name: " << this -> name << endl; }
} }
};

Note: this is only strictly necessary when the parameter name shadows the instance variable name. If
the parameter was String n, then name = n; would suffice.

Example
class Student {
int id;
public:
void setId(int id) {
this->id = id; // disambiguates between member and parameter
}
};

13
Shallow and Deep Copy

abhishekshinde5805@[Link]
1. Shallow Copy
• Copies reference/address of dynamic members.
• Both objects share the same memory.
• Changing data in one object affects the other.
• Example: Photocopy of a key (looks same, but linked).
2. Deep Copy
• Creates new memory and copies the actual value.
• Both objects are independent.
• Modifying one object does not affect the other.
• Example: Making a new key from scratch (fully separate).
Examples

Shallow Copy Deep Copy

C++ C++

#include <iostream> #include <iostream>


using namespace std; using namespace std;

class Student { class Student {


public: public:
int* marks; int* marks;

Student(int m) { Student(int m) {
marks = new int(m); marks = new int(m);
} }

// Shallow Copy // Deep Copy


Student(const Student& s) { Student(const Student& s) {
marks = [Link]; // copies address only marks = new int(*([Link])); // allocates
} and copies value
}
void show() {
cout << "Marks: " << *marks << endl; void show() {
} cout << "Marks: " << *marks << endl;
}; }
};
int main() {
Student s1(90); int main() {
Student s2 = s1; Student s1(90);
*[Link] = 50; Student s2 = s1;
*[Link] = 50;
[Link](); // Marks: 50 ❌
} [Link](); // Marks: 90 ✔
[Link](); // Marks: 50 ✔}

14
Java Java

abhishekshinde5805@[Link]
class Student { class Student {
int[] marks; int[] marks;

Student(int m) { Student(int m) {
marks = new int[1]; marks = new int[1];
marks[0] = m; marks[0] = m;
} }

// Shallow Copy // Deep Copy


Student(Student s) { Student(Student s) {
[Link] = [Link]; // copy reference only [Link] = new int[1];
} [Link][0] = [Link][0]; // copy value
}
void show() {
[Link]("Marks: " + marks[0]); void show() {
} [Link]("Marks: " + marks[0]);
} }
}
public class Main {
public static void main(String[] args) { public class Main {
Student s1 = new Student(90); public static void main(String[] args) {
Student s2 = new Student(s1); Student s1 = new Student(90);
Student s2 = new Student(s1);
[Link][0] = 50;
[Link][0] = 50;
[Link](); // Marks: 50 ❌
[Link](); // Marks: 50 [Link](); // Marks: 90 ✔
} [Link](); // Marks: 50 ✔
} }
}

15
Inheritance

abhishekshinde5805@[Link]
• One class (Child / Derived) inherits properties and behavior from another (parent / base).
• Promotes code reuse and hierarchical structure.
Real life Example: A child inherits traits like eye color and height from their parents.

C++ Java

// Parent or Base Class // Parent or Base Class


class Vehicle { class Vehicle {
public: void start() {
void start() { [Link]("Vehicle started");
cout << "Vehicle started" << endl; }
} }
}; // Child or Derived Class
// Child or Derived Class // Car inherits from Vehicle
// Car inherits from Vehicle class Car extends Vehicle {
class Car : public Vehicle { void drive() {
public: [Link]("Car is driving");
void drive() { }
cout << "Car is driving" << endl; }
}
};

Modes of Inheritance
(Only in C++)
• Describes how inheritance affects access control.
• When a class inherits from another, it can do so using different access modes:

1. class Derived : public Base // public inheritance

2. class Derived : protected Base // protected inheritance

3. class Derived : private Base // private inheritance

• Control how the members of the base class are treated in the derived class.

Access Modifier Behaviour


Base Member Public Inheritance Protected Inheritance Private Inheritance

public public protected private

protected protected protected private

private Not inherited Not inherited Not inherited

NOTE: Java does not support inheritance modes like C++ while all inheritance is effectively
public via extends.
NOTE: Private members are not directly accessible in the derived class, but they still exist
within the base class portion of the derived object and can be manipulated via public/protected
methods of the base class.

16
Types of Inheritance

abhishekshinde5805@[Link]
1. Single Inheritance
• A class is allowed to inherit from only one class.
• A derived class inherits from one base class.
• Parent → Child

C++ Java

class A { class A {
public: public void showA() {
void showA() { [Link]("Base Class A");
cout << "Base Class A\n"; }
} }
};
class B extends A {
class B : public A { public void showB() {
public: [Link]("Derived Class B");
void showB() { }
cout << "Derived Class B\n"; }
}
};

2. Multilevel Inheritance
• A class is derived from a class which is already derived from another
class.
• Parent → Child → Grandchild

C++ Java

class A { class A {
public: public void showA() {
void showA() { [Link]("Class A (Base)");
cout << "Class A (Base)\n"; }
} }
};
class B extends A {
class B : public A { public void showB() {
public: [Link]("Class B (Derived from
void showB() { A)");
cout << "Class B (Derived from A)\n"; }
} }
};
class C extends B {
class C : public B { public void showC() {
public: [Link]("Class C (Derived from
void showC() { B)");
cout << "Class C (Derived from B)\n"; }
} }
};

17
3. Hierarchical Inheritance
● Multiple classes inherit from a single base class.

abhishekshinde5805@[Link]
● One base → multiple derived classes

C++ Java

class A { class A {
public: public void showA() {
void showA() { [Link]("Class A (Base)");
cout << "Class A (Base)\n"; }
} }
};
class B extends A {
class B : public A { public void showB() {
public: [Link]("Class B (Derived from
void showB() { A)");
cout << "Class B (Derived from A)\n"; }
} }
};
class C extends A {
class C : public A { public void showC() {
public: [Link]("Class C (Also derived
void showC() { from A)");
cout << "Class C (Also derived from A)\n"; }
} }
};

4. Multiple Inheritance
● A single class inherits from two or more base classes.
● One class inherits from multiple base classes.

Does Java support Multiple inheritance?


● No - Does not support using Classes.
● Yes - Supports using Interfaces.

Why does Java not support Multiple inheritance using classes?


● It leads to ambiguity.
● Ambiguity in inheritance occurs when a class inherits from multiple classes that have
methods or members with the same name - making it unclear which one should be
called.

What is Interface?
● It is a Contract that defines a set of methods (without implementations) that a class
must implement.

18
C++ Java

Supports multiple inheritance directly using classes. Supports multiple inheritance directly using interfaces.

abhishekshinde5805@[Link]
class A { interface A {
public: public void showA();
void showA() { }
cout << "Class A\n";
interface B {
}
public void showB();
};
}
class B {
class C implements A, B {
public:
public void showA() {
void showB() {
[Link]("From Interface A");
cout << "Class B\n";
}
}
}; public void showB() {
[Link]("From Interface B");
class C : public A, public B {
}
public:
void showC() { public void showC() {
cout << "Class C (Derived from A and B)\n"; [Link]("Class C implementing A
} and B");
}; }
}

5. Hybrid Inheritance
● A combination of two or more types of inheritance (like multiple + multilevel).

C++ Java

class A { interface A {
public: public void showA();
void showA() { cout << "Class A\n"; } }
};
interface B extends A {
public void showB();
class B : public A {
}
public:
void showB() { cout << "Class B (Derived from interface C extends A {
A)\n"; } public void showC();
}; }
class D implements B, C {
class C : public A {
public void showA() {
public:
[Link]("From Interface A");
void showC() { cout << "Class C (Also derived
}
from A)\n"; }
}; public void showB() {
[Link]("From Interface B");
class D : public B, public C { }
public:
public void showC() {
void showD() { cout << "Class D (Derived from
[Link]("From Interface C");
B and C)\n"; }
}
};
public void showD() {
[Link]("Class D implementing B
and C");
}
}

19
The Diamond Problem

abhishekshinde5805@[Link]
• Multiple inheritance issue where a class inherits from two classes
that share a common base class, causing ambiguity in inheritance.
• Class B and Class C both inherit from A.
• Class D inherits from both B and C.
• Now, if D accesses something from A, the compiler doesn’t know
whether to use the copy inherited through B or through C — this is
called the diamond problem and it occurs in multiple inheritance.

The Example in C++ (How Diamond Problem Arises)

#include <iostream>
using namespace std;

class A {
public:
void show() {
cout << "Class A" << endl;
}
};

class B : public A { };
class C : public A { };

// Diamond Problem arises here


class D : public B, public C { };

int main() {
D obj;
// [Link](); Ambiguity: from B or C?
obj.B::show(); // Manually resolved
obj.C::show();
return 0;
}

Virtual inheritance:
• Virtual inheritance in C++ ensures that only one copy of a base class is inherited when
multiple derived classes share it.
• It prevents the diamond problem by making sure that the shared base class is not
duplicated in the inheritance chain.

20
Solution in C++: Virtual Inheritance

#include <iostream>

abhishekshinde5805@[Link]
using namespace std;

class A {
public:
void show() {
cout << "Class A" << endl;
}
};

//Virtual Inheritance
class B : virtual public A { };
class C : virtual public A { };
class D : public B, public C { };

int main() {
D obj;
[Link](); // No ambiguity
}

What about Java?


• Java’s Approach – No Diamond Problem.
• Java does not allow multiple class inheritance, so the diamond problem does not
occur with classes.
• Java uses interfaces for safe multiple inheritance.

Using Interfaces – Java’s Safe Multiple Inheritance

interface A {
void show();
}

interface B extends A { }
interface C extends A { }

class D implements B, C {
public void show() {
[Link]("Class D implementing show()");
}
}

● No ambiguity in the above example because D is forced to define its own show() method.

21
Polymorphism

abhishekshinde5805@[Link]
• Ability of objects to take on different forms or behave in different ways depending on the
context in which they are used.
or
• Polymorphism means "many forms": the ability of a function, method, or object to behave
differently in different contexts.

Real-life Example: The same person acts as a student at college, a player on the field, and
a child at home - different roles, same individual.

Different Behaviors:
1. In Shopping Mall, Behave Like a Customer
2. In Class Room, Behave Like a Student
3. In Bus, Behave Like a Passenger
4. In Home, Behave Like a Son or Daughter

Types of Polymorphism
1. Compile-time Polymorphism / Static Binding
Achieved by:
• Function/Method Overloading (Java & C++)
• Operator Overloading (C++ only)

2. Runtime Polymorphism / Dynamic Binding


Achieved by:
• Method Overriding (Java & C++)
• Virtual Functions (C++)

Compile-time Polymorphism (Static Binding)


• Also known as early binding
• Compile-time polymorphism means that the method to be executed is determined at
compile time, based on the method signature (name + parameters).
• Same method name, different parameter lists → the correct method is selected by the
compiler.

Real life Example: You can call someone using their name, number, or nickname - all are
valid ways to "call", depending on what info you have.

1. Method Overloading:
Allows a class to have more than one method with the same name but different
parameters (number, type, or order).

22
C++ Java

class Calculator { class Calculator {

abhishekshinde5805@[Link]
public: int add (int a, int b) {
int add (int a, int b) { return a + b;
return a + b; }
}
double add (double a, double b) {
double add (double a, double b) { return a + b;
return a + b; }
}
int add (int a, int b, int c) {
int add (int a, int b, int c) { return a + b + c;
return a + b + c; }
} }
};

Rules for Method Overloading:


• Method name must be same
• Parameters must be different (type, number, or order)
• Return type alone doesn’t matter

2. Operator Overloading:
• Allows to redefine the behavior of operators (+, -, , etc.) for user-defined types
(classes/objects).

C++

class Complex {
public:
int real, imag;

Complex(int r, int i) {
real = r;
imag = i;
}

// Overload '+' operator


Complex operator + (const Complex& obj) {
return Complex(real + [Link], imag + [Link]);
}

void show() {
cout << real << " + " << imag << "i" << endl;
}
};

int main() {
Complex c1(2, 3), c2(1, 4);
Complex c3 = c1 + c2;
[Link](); // Output: 3 + 7i
}

• Java does not support operator overloading (except for + used with Strings).

23
Run-time Polymorphism (Dynamic Binding)

abhishekshinde5805@[Link]
• Also called dynamic method dispatch / late binding
• In runtime polymorphism, the method that is executed is determined at runtime, not at
compile-time.
• It allows us to call the correct overridden method based on the actual object type, even
if we are using a base class reference or pointer.
• Same method name is called via base type but behaves based on the derived object.

Real life Example: You call makeSound() on an Animal, but whether it barks or meows
depends on whether the object is a Dog or Cat — this decision is made at runtime

1. Method Overriding:
• Method overriding means redefining a base class method in a derived class using
the same method name, parameters, and return type.
• It allows a derived class to provide its own implementation of a method defined in
its base class.

C++ Java

class Animal { class Animal {


public: public void speak() {
virtual void speak() { [Link]("Animal speaks");
cout << "Animal speaks" << endl; }
} }
};
class Dog extends Animal {
class Dog : public Animal { @Override
public: public void speak() {
void speak() override { [Link]("Dog barks");
cout << "Dog barks" << endl; }
} }
};
public class Main {
int main() { public static void main(String[] args) {
Animal* a = new Dog(); Animal a = new Dog();
a->speak(); // Output: Dog barks [Link](); // Output: Dog barks
delete a; }
} }

Rules for Method Overriding:


• Method name must be same
• Parameter list must match exactly
• Return type must be same

NOTE: Use of virtual keyword (C++): The virtual keyword enables dynamic binding,
allowing the correct overridden method to be called at runtime when using base class pointers
or references. Without it, the base class method is always called.

24
Feature Overloading Overriding

Definition Same method name, different Same method name and signature

abhishekshinde5805@[Link]
parameters in same class in parent and child classes

Type of Polymorphism Compile-time (Static) Runtime (Dynamic)

Inheritance Required? Not required Required (involves inheritance)

Class Involved Happens within the same class Happens between base and
derived class

Parameters Must be different in number / type Must be exactly same


/ order

Return Type Can differ (but return type alone Must be same or covariant (in Java)
can’t overload)

Virtual Functions
(Only in C++)
• Member function in the base class that you expect to be overridden in derived classes.
• Declaring a function virtual tells the compiler to use runtime (dynamic) binding instead
of compile-time (static) binding.

Why use virtual Functions?


● Without virtual, C++ binds functions at compile-time based on the pointer/reference
type, not the actual object type.
● With virtual, C++ defers the decision until runtime, so the correct overridden function is
called.

C++

class Animal {
public:
// Virtual Function
virtual void speak() {
cout << "Animal speaks" << endl;
}
};

class Dog : public Animal {


public:
void speak() override {
cout << "Dog barks" << endl;
}
};

int main() {
Animal* a = new Dog(); // base pointer → derived object
a->speak(); // Output: Dog barks
delete a;
}

• Without virtual, this would print "Animal speaks".

25
Abstraction

abhishekshinde5805@[Link]
● Hiding all the unnecessary / internal implementation details and showing only the
relevant / essential features.
● Achieved via abstract classes with pure virtual functions (C++) or abstract classes /
interfaces (Java).
Real life Example: You use a smartphone by tapping icons, without knowing the internal code
behind apps.
NOTE: In C++, abstraction can be partially achieved using access specifiers, but full
abstraction is implemented through abstract classes with pure virtual functions.

Abstract Classes and Pure Virtual Functions


(Only in C++)
Abstract Class:
● Class that cannot be instantiated.
● Contains at least one pure virtual function.
● Provides a base interface that must be implemented by derived classes.

Pure Virtual Function:


● Function declared in a base class that has no definition in that class and must be
overridden in derived classes.
● The = 0 makes a function, a pure virtual function.

Abstract Class with Pure Virtual Function

#include <iostream>
using namespace std;

// Abstract class
class Shape {
public:
// Pure virtual function
virtual void area() = 0;

void display() {
cout << "This is a shape.\n";
}

// Virtual destructor
virtual ~Shape() {
cout << "Shape destroyed\n”;
}
};

// Derived class 1
class Circle : public Shape {
public:
void area() override {
cout << "Area of Circle: π * r * r\n";
}
};

26
// Derived class 2
class Rectangle : public Shape {
public:

abhishekshinde5805@[Link]
void area() override {
cout << "Area of Rectangle: length * breadth\n";
}
};

int main() {
// Shape s; => Not allowed: cannot instantiate abstract class

Shape* s1 = new Circle();


s1->area(); // Output: Area of Circle
s1->display(); // Output: This is a shape.

Shape* s2 = new Rectangle();


s2->area(); // Output: Area of Rectangle
s2->display(); // Output: This is a shape.

delete s1;
delete s2;
}

● You have a base class Shape, but you don’t want anyone to create a generic shape - only
specific shapes like Circle or Rectangle.
● So, Shape becomes an abstract class with area as a pure virtual function, and you force
child classes to implement the method area ().

Abstract Class in Java / Interface in Java


(Only in Java)

Abstract Class:
● Cannot be instantiated (i.e., you can't create its objects directly)
● Can contain abstract methods (without body)
● Can also contain concrete methods (with body)
● Can have fields, constructors, and access modifiers

Abstract Class

abstract class Animal {


String name;

Animal(String name) {
[Link] = name;
}

public abstract void makeSound(); // must be overridden

public void sleep() {


[Link](name + " is sleeping");
}
}

27
Interfaces:
● Is a contract - it defines what a class must do, but not how

abhishekshinde5805@[Link]
● Can have abstract methods (no body), default methods (with body), static method
● Cannot have constructors or instance variables

Interface

interface Flyable {
void fly(); // abstract method

default void land() {


[Link]("Landing...");
}

static void info() {


[Link]("Flyable interface");
}
}

Feature Abstract Class Interface

Inheritance extends (single class only) implements (multiple interfaces allowed)

Constructors Yes No

Fields Instance and static fields allowed Only public static final (constants)

Abstract Methods Yes Yes

Concrete Methods Yes Yes (via default and static)

Access Modifiers Any (private, protected, etc.) Methods are public by default

Instantiation Cannot be instantiated Cannot be instantiated

Use Case Shared base logic Capability/behavior declaration

Supports Multiple
No Yes
Inheritance

28
Static Data Member and Function

abhishekshinde5805@[Link]
Static Data Member Static Member Function

A static data member is a variable that is shared A static member function belongs to the class
by all objects of a class. rather than any object.

It is allocated only once in memory, and any It can be called without creating an object, and
change made by one object is reflected across it can only access static members.
all.

Example: Example:
static int count; static void showCount() {
cout << count;
}

● Shared among all instances of the class ● Called using ClassName::showCount() in


● Exists even before any object is created C++
● Called using [Link]() in
Java
● Static member functions cannot access
non‑static members directly.

29
MCQs:
1. Which of the following is not a 7. Which concept is violated if a
feature of OOP? constructor calls itself recursively

abhishekshinde5805@[Link]
A. Encapsulation without termination in C++/Java?
B. Polymorphism A. Encapsulation
C. Compilation B. Abstraction
D. Inheritance C. Infinite recursion (stack overflow)
D. Overloading
2. Which access modifier allows
visibility within the same package
8. Which inheritance is not supported
only?
in Java but is in C++?
A. private
A. Single
B. protected
B. Multilevel
C. public
C. Multiple
D. default
D. Hierarchical
3. Which access specifier makes
class members accessible to 9. What keyword does Java use to
derived classes but not outside the resolve method conflicts in multiple
class? inheritance via interfaces?
A. private A. extends
B. protected B. override
C. public C. implements
D. friend D. super

4. Which of the following is true about 10. In C++, what is the default visibility
'protected' members? mode for class inheritance?
A. Only accessible within the same A. public
class B. private
B. Accessible in same package and C. protected
subclasses D. depends on access specifier
C. Accessible everywhere
D. Accessible only in subclasses 11. Which problem does virtual
inheritance solve in C++?
5. Which statement is true about A. Constructor overloading
constructors in C++? B. Diamond problem
A. Constructor returns a value C. Ambiguous operator overloading
B. Constructor can be virtual D. Memory leak
C. Constructors can be overloaded
D. Constructors cannot take parameters 12. Function overloading is resolved
during which time?
6. Which of the following is a correct A. Runtime
way to overload constructors in B. Compile-time
Java? C. Execution
A. By changing access specifiers D. Interpretation
B. By changing method name
C. By changing return type
D. By changing number/types of
parameters

30
13. Method overriding requires which 19. Which of the following best
condition in Java? represents encapsulation?
A. Different method names A. Hiding data behind methods

abhishekshinde5805@[Link]
B. Same method signature in subclass B. Using inheritance
C. Same return type only C. Overriding methods
D. Final methods D. Global variables

14. Which method cannot be overridden 20. Which of the following cannot be
in Java? achieved using abstraction?
A. Static methods A. Hiding internal logic
B. Abstract methods B. Code modularity
C. Public methods C. Tight coupling
D. None D. Implementation hiding

15. In C++, what happens if a virtual 21. In Java, what happens if a subclass
function is not overridden in a overrides a method and calls
derived class? [Link]() inside it?
A. Compile-time error A. Infinite recursion
B. Parent’s version gets called B. Calls parent class’s method
C. Runtime error C. Compile-time error
D. Object slicing occurs D. Method gets hidden

16. Which of the following is true about 22. In C++, what happens if you delete
abstract classes in Java? a derived class object using a base
A. Can be instantiated class pointer without a virtual
B. Must contain abstract methods destructor?
C. Can contain constructors A. Only base destructor called
D. Cannot have variables B. Both destructors called
C. Segmentation fault
17. Which statement is false about D. Compile-time error
interfaces in Java?
A. All methods are public and abstract 23. Which keyword is used in Java to
by default prevent method overriding?
B. Interfaces support multiple A. final
inheritance B. static
C. Can contain constructors C. abstract
D. Can contain static methods D. protected

18. In C++, what makes a class 24. How much memory does a class
abstract? occupy?
A. A constructor A. Memory equal to all its members
B. A destructor B. Depends on number of member
C. At least one pure virtual function functions
D. No methods at all C. Zero until object is created
D. Same as its parent class

31
25. Is it always necessary to create 31. Which C++ operator is used to
objects from a class? deallocate memory?
A. Yes, for every class A. free

abhishekshinde5805@[Link]
B. No, static members can be accessed B. malloc
without objects C. delete
C. Only in C++, not in Java D. clear
D. Only for abstract classes
32. Java manages memory automatically
26. Which of the following is true about using:
static methods in Java? A. Smart pointers
A. Can access instance variables B. new/delete
B. Belong to the object C. Garbage Collection
C. Cannot be called from another D. Free ()
static method
D. Can be called without creating 33. In Java, ‘this’ keyword refers to:
object A. Parent object
B. Static reference
27. In C++, static members are shared C. Current object
across: D. Superclass
A. Only base class
B. Only objects 34. Which of the following can’t be
C. All objects of the class virtual in C++?
D. Inherited classes only A. Constructor
B. Member function
28. What is the size of an empty class C. Destructor
in C++? D. Operator overload
A. 0
B. 1 35. Which of the following cannot be
C. 2 inherited in Java?
D. Depends on compiler A. final class
B. abstract class
29. Which of the following can be C. interface
overloaded but not overridden? D. protected class
A. static methods
B. virtual functions 36. What will the following Java code
C. constructors output?
D. destructors class Test {
public static void main(String[] args) {
30. In Java, memory for objects is Test t1 = new Test();
allocated using: Test t2 = t1;
A. malloc [Link](t1 == t2);
B. new }
C. calloc }
D. constructor A. true
B. false
C. Compile error
D. Runtime error

32
37. In C++, which constructor is A. Compile-time error
invoked if no arguments are B. Child
passed? C. Parent

abhishekshinde5805@[Link]
A. Copy constructor D. Runtime exception
B. Parameterized constructor
C. Default constructor 42. What will the C++ code below print?
D. None class Base {
public:
38. In Java, what happens when we virtual void show() { cout << "Base\n"; }
make an interface reference refer to };
a class object? class Derived : public Base {
A. Only methods of interface are public:
accessible void show() { cout << "Derived\n"; }
B. All methods are accessible };
C. Throws error int main() {
D. Calls constructor of interface Base obj;
Derived d;
39. Can we create an object of abstract obj = d;
class in C++ using pointer? [Link]();
A. Yes, always }
B. Yes, but only if not calling pure A. Base
virtual methods B. Derived
C. No C. Compile error
D. Yes, but can't instantiate it D. Undefined

40. Can an abstract class have a 43. Why use abstract class over interface
constructor in Java? in Java?
A. No A. You need multiple inheritance
B. Yes B. You want to define method
C. Only if all methods are abstract contracts only
D. Only if it has no instance variables C. You want to share common code
D. You want to use default methods
41. What is the output of the following
Java code? 44. What is called automatically when
class Parent { an object goes out of scope in C++?
void show() { A. Destructor
[Link]("Parent"); } B. Garbage collector
} C. Free ()
class Child extends Parent { D. Finalize
void show() { [Link]("Child");
} 45. Which of the following is true about
} finalize() in Java?
class Test { A. It must be manually called
public static void main(String[] args) { B. It is guaranteed to execute before
Parent p = new Child(); object is garbage collected
[Link](); C. It is deprecated in Java 9+
} D. It is used in C++ for memory
} cleanup

33
ANSWER KEY
1. (C) 2. (D) 3. (B) 4. (B) 5. (C)

abhishekshinde5805@[Link]
6. (D) 7. (C) 8. (C) 9. (D) 10. (B)
11. (B) 12. (B) 13. (B) 14. (A) 15. (B)
16. (C) 17. (C) 18. (C) 19. (A) 20. (C)
21. (B) 22. (A) 23. (A) 24. (C) 25. (B)
26. (D) 27. (C) 28. (B) 29. (C) 30. (B)
31. (C) 32. (C) 33. (C) 34. (A) 35. (A)
36. (A) 37. (C) 38. (A) 39. (C) 40. (B)
41. (B) 42. (A) 43 (C) 44. (A) 45. (C)

EXPLANATION

1. Compilation is a programming concept, not an OOP principle. OOP is based on


encapsulation, inheritance, and polymorphism.
2. Default (package-private) gives access only within the same package.
3. Protected members are accessible in derived classes but not outside of the class
hierarchy.
4. Protected gives access within the same package and to subclasses in other packages.
5. C++ supports constructor overloading with different parameter types.
6. Constructor overloading in Java is done by varying parameter lists.
7. Recursion without a base case leads to stack overflow error.
8. Java does not support multiple inheritance using classes.
9. super is used to specify which interface’s method to call.
10. C++ classes default to private inheritance unless specified otherwise.
11. Virtual inheritance avoids multiple "Base" class copies in diamond structures.
12. Overloading is compile-time polymorphism.
13. Method overriding requires same name, signature, and return type.
14. Static methods are class-level and can’t be overridden.
15. Base class version is called if not overridden.
16. Abstract classes can have constructors and variables.
17. Interfaces cannot have constructors.
18. A class becomes abstract with at least one pure virtual function.
19. Encapsulation hides internal state using access modifiers.
20. Abstraction promotes loose coupling.
21. [Link]() calls the overridden method in the parent class.

34
22. Not using a virtual destructor causes undefined behavior; only base destructor is invoked.
23. The final keyword prevents overriding.

abhishekshinde5805@[Link]
24. In both Java and C++, a class does not occupy memory until an object is created. Memory
is only allocated for instances, not for the class blueprint itself (except for static members,
which are shared).
25. It is not always required to create objects. You can access static members and use a
class as a utility (like Math class in Java) without creating an instance.
26. Static methods are class-level and can be called without an object.
27. Static members are common to all instances of a class.
28. C++ allocates 1 byte to ensure unique addresses for objects.
29. Constructors can't be inherited or overridden but can be overloaded.
30. Java uses the new keyword to allocate memory.
31. delete deallocates memory allocated using new.
32. Java’s JVM includes a garbage collector.
33. This refers to the current object instance.
34. Constructors cannot be virtual in C++.
35. Final classes cannot be extended.
36. Both references point to the same object; hence true.
37. Default constructor is used when no arguments are passed.
38. Only methods declared in the interface are accessible.
39. Cannot instantiate abstract class, even via pointer.
40. Abstract classes can have constructors for initialization.
41. This is runtime polymorphism. Child's overridden method is called.
42. Object slicing occurs; Base version is called.
43. Abstract classes allow sharing implementation logic.
44. Destructor is invoked automatically on scope end.
45. finalize() is deprecated due to unpredictability and performance issues.

35

You might also like