Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
18 views45 pages

OOPs Complete Notes

The document provides a comprehensive overview of Object-Oriented Programming (OOP) concepts, including classes, objects, inheritance, encapsulation, and polymorphism. It contrasts Object-Oriented Programming with Procedural-Oriented Programming, highlighting differences in approach, security, and modularity. Additionally, it covers constructors and destructors, detailing their types and usage in various programming languages such as Java, C++, and Python.

Uploaded by

viralkira2
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)
18 views45 pages

OOPs Complete Notes

The document provides a comprehensive overview of Object-Oriented Programming (OOP) concepts, including classes, objects, inheritance, encapsulation, and polymorphism. It contrasts Object-Oriented Programming with Procedural-Oriented Programming, highlighting differences in approach, security, and modularity. Additionally, it covers constructors and destructors, detailing their types and usage in various programming languages such as Java, C++, and Python.

Uploaded by

viralkira2
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
You are on page 1/ 45

OOPs Infeepedia By: Infee Tripathi

Syllabus of OOPs
Review of Fundamentals of Procedural Programming, Class and Objects, Data Abstraction, Information Hiding &
Encapsulation, Constructors, destructors, and object creation, Name space and references , Class Methods , Methods
Overloading , Inheritance , Polymorphism , Abstract Classes, Abstract Methods , Exceptions , Exception Handling.

Procedural oriented programming Vs Object Oriented Programming


SNo. POPS OOPS

1. Top down approach Bottom up approach

2. Based on functions, procedures or subroutines Based on real world objects which contains data and
method.

3. Complex to implement large applications. Easy to implement large projects.

Subscribe Infeepedia youtube channel for computer science competitive exams


Download Infeepedia app and call or wapp on 8004391758
OOPs Infeepedia By: Infee Tripathi
4. It is less secure Highly secure

5. Overloading is allowed. Overloading is not allowed

6. Less modularity; functions are interdependent. High modularity; objects can be reused and modified
independently.
7. C, Pascal, Fortran. Java, C++, Python, C#.

Object oriented programming concepts

 Class
 Objects
 Inheritance
 Encapsulation
 Abstraction
 Polymorphism

Class
 A class is a user-defined blueprint or prototype used to create objects.
 It is a logical entity containing data members (variables defining the object's state) and member functions (methods
defining the object's behavior).
 Memory is not allocated to classes, as they have no physical existence, unlike objects which are physical entities.
 Classes cannot be manipulated directly due to the lack of memory allocation, but objects can be.
 Access specifiers in classes control the visibility of data members and methods. By default, members are private if no
access specifier is mentioned.
 Member functions can be defined in two ways:
 Inside the class: Defined directly within the class definition.
 Outside the class: Defined using the scope resolution operator (::) (in C++ )with the class name and function name.
In Python, member functions cannot be defined outside the class. However, you can use functions outside the class and
pass the class object as a parameter to simulate similar behavior.

Subscribe Infeepedia youtube channel for computer science competitive exams


Download Infeepedia app and call or wapp on 8004391758
OOPs Infeepedia By: Infee Tripathi
Java CPP Python
class ClassName class ClassName class ClassName:
{ {
// Data members (variables) private: # Constructor
int dataMember; // Data members def __init__(self):
int dataMember;
// Constructor # Initialization code
ClassName() public: self.data_member = 0
{ // Constructor
// Initialization code ClassName() # Member function
} { def member_function1(self):
// Initialization code # Function code
// Member function } pass
void memberFunction1()
{ // Member function # Function outside the class
// Function code void memberFunction1() def member_function2(ClassName):
} { # Function code
// Function code pass
// member function declaration }
void memberFunction2(); # Creating an object of the class
} // Member function declaration obj = ClassName()
void memberFunction2 (); obj.member_function1()
// Function definition outside the }; member_function2(obj)
class
void ClassName:: memberFunction2 () // Function definition outside the class
{ void ClassName:: memberFunction2 () {
// Function code // Function code
} }

public static void main(String[] args) int main()


{ {
// Creating an object of the class // Creating an object of the class
ClassName obj = new ClassName(); ClassName obj;
obj.memberFunction1(); obj.memberFunction1();
obj.memberFunction2(); obj.memberFunction2();
} return 0;
} }

Objects
 An object is a real-world entity, like a chair, car, or mobile.
 Objects are created to access the data and methods of a class.
 They allow access to the class's data and member functions.
 Data defines an object's state, and methods define its behavior.
 Objects encapsulate data and behavior, ensuring better modularity and reusability in
programs.
 Memory is allocated to objects, and their size depends on the class's data members.
 Multiple objects and array-type objects can be created for a class.
 Each object has its own copy of the class's non-static data members, ensuring they maintain independent
states.
 Objects can also interact with one another by calling each other's methods or accessing shared data.

Subscribe Infeepedia youtube channel for computer science competitive exams


Download Infeepedia app and call or wapp on 8004391758
OOPs Infeepedia By: Infee Tripathi
Java CPP Python
class Car #include <iostream> class Car:
{ using namespace std; def __init__(self, model, year):
String model; class Car self.model = model
int year; { self.year = year
Car(String model, int year) public: def display(self):
{ string model; print(f"Model: {self.model}, Year:
this.model = model; int year; {self.year}")
this.year = year; Car(string m, int y)
} { car1 = Car("Toyota", 2020)
void display() model = m; car2 = Car("Honda", 2022)
{ year = y;
System.out.println("Model: " + model + } car1.display()
", Year: " + year); void display() car2.display()
} {
} cout << "Model: " << model << ", Year:
public class Main " << year << endl; }
{ };
public static void main(String[] args) int main()
{ {
Car car1 = new Car("Toyota", 2020); Car car1("Toyota", 2020);
Car car2 = new Car("Honda", 2022); Car car2("Honda", 2022);
car1.display(); car1.display();
car2.display(); car2.display();
} return 0;
} }

Constructor
 Constructors are special member functions used to initialize objects of a class.
 They have the same name as the class and no return type(in C++ and java).
 Automatically invoked when an object is created, constructors set initial values for the object's attributes.
 They can be overloaded but cannot be declared virtual or inherited.
 A constructor's address cannot be referenced.
 Constructors must be placed in the public section of a class.
 They can be defined either inside or outside the class declaration.
 In Java, constructors can call other constructors in the same class using this().
 In Python, the constructor is defined using the __init__() method.
 In Java and Python, constructors are tightly integrated with the class structure, ensuring encapsulation and simplicity in
object creation and cannot declare or define outside the class.
 In C++ constructors can be declared or defined outside the class.

Syntax of Constructors: Syntax of Declaring a Constructor Syntax of Declaring a Constructor


<class-name> (list-of-parameters);
<class-name>(list-of-parameters) { def __init__(self, list_of_parameters):
Syntax for Defining the Constructor Within // Constructor definition # Constructor definition
the Class }
<class-name> (list-of-parameters)
{
// constructor definition
}

Subscribe Infeepedia youtube channel for computer science competitive exams


Download Infeepedia app and call or wapp on 8004391758
OOPs Infeepedia By: Infee Tripathi
Syntax for Defining the Constructor
Outside the Class
<class-name>::<class-name>(list-of-
parameters)
{
// constructor definition
}

Types of Constructor
Based on the situations they are being used constructor is classified in 3 types.
1. Default Constructor
2. Parameterized Constructor
3. Copy Constructor

1. Default constructor
 A default constructor is a constructor that takes no arguments and has no parameters. ‘
 It initializes the object's attributes with default values.
 It is also called a zero-argument constructor.
 Automatically provided by the compiler if no constructor is explicitly defined.
 Used to initialize objects with default values.
 If a class has at least one user-defined constructor, the compiler does not generate a default constructor.
 In Java and C++, the compiler automatically provides a no-argument constructor if no constructors are explicitly defined.
If a user-defined constructor is present, the default constructor is not generated.
 In Python, the default constructor is defined using the __init__() method with no parameters except self. If no
constructor is explicitly defined, Python does not generate a default constructor automatically.

Java C++ Python


class Student #include <iostream> class Student:
{ using namespace std; def __init__(self):
String name; class Student self.name = "Unknown"
int age; { self.age = 0
Student() // Default Constructor private: def display(self):
{ string name; print(f"Name: {self.name}, Age:
name = "Unknown"; int age; {self.age}")
age = 0; public: s = Student() # Default constructor
} Student() // Default Constructor is invoked
void display() { s.display()
{ name = "Unknown";
System.out.println("Name: " + name + ", age = 0;
Age: " + age); }
} void display()
} {
public class Main cout << "Name: " << name << ", Age: "
{ << age << endl; }
public static void main(String[] args) };
{ int main()
Student s = new Student(); // Default {
constructor is invoked Student s; // Default constructor is
s.display(); invoked
} s.display();
} return 0; }
Subscribe Infeepedia youtube channel for computer science competitive exams
Download Infeepedia app and call or wapp on 8004391758
OOPs Infeepedia By: Infee Tripathi
2. Parameterized Constructors
 A parameterized constructor is a constructor that takes arguments to initialize an object with specific values.
 It allows passing values as arguments when creating an object.
 Parameters are used within the constructor body to initialize the object's attributes.
 When using a parameterized constructor, initial values must be passed during object creation.
 Normal object declaration (e.g., Car c;) will not work if no default constructor is defined.
 Parameterized constructors can be called explicitly or implicitly:
o Explicit Call: Car c = Car("Swift", "Red", 500);
o Implicit Call: Car c("Swift", "Red", 500); (only in C++ but not in java and python).
 If a parameterized constructor is defined and no default constructor is provided explicitly, the compiler will not implicitly
generate a default constructor. Creating an object without arguments (car c) will result in an error.
 Java does not support implicit calls to constructors. Objects must be created using the new keyword.
Example: Car c = new Car("Swift", "Red", 500);.
 In Java it does not support default arguments in constructors. Instead, constructor overloading is used to achieve similar
functionality.

 C++ supports both explicit and implicit calls to parameterized constructors. It fully supports default arguments in
constructors.
 In Python constructors are defined using __init__(). Parameterized constructors are the most common type in Python.
Default arguments allow flexible object creation without needing multiple constructors.

 Whenever we define one or more non-default constructors( with parameters ) for a class, a default constructor( without
parameters ) should also be explicitly defined as the compiler will not provide a default constructor in this case.
 It is used to initialize the various data elements of different objects with different values when they are created.
 It is used to overload constructors.
 We can also define default values for the arguments of parameterized constructors Just like normal functions. All the
rules of the default arguments will be applied to these parameters.
 When the default values are assigned to every argument of the parameterized constructor, it is allowed to create the
object without passing any parameters just like default constructors.
 This type of constructor works as both a default and parameterized constructor.

Note:- A default argument is a value provided in a function declaration that is automatically assigned by the compiler if the
calling function doesn’t provide a value for the argument. In case any value is passed, the default value is overridden.

Java CPP Python


class Car #include <iostream> class Car:
{ using namespace std; def __init__(self, model="Unknown",
String model; class Car color="Unknown", price=0):
String color; { self.model = model
int price; private: self.color = color
// Default Constructor string model; self.price = price
Car() string color; def display(self):
{ int price; print(f"Model: {self.model}, Color:
this.model = "Unknown"; public: // Parameterized Constructor {self.color}, Price: {self.price}")
this.color = "Unknown"; with Default Arguments
this.price = 0; Car(string m = "Unknown", string c = # Creating objects
} "Unknown", int p = 0) c1 = Car() # Default arguments used
// Parameterized Constructor { c2 = Car("Swift", "Red", 500) # Explicit
Car(String model, String color, int price) model = m; arguments override defaults
{ color = c; c1.display()
this.model = model; price = p; c2.display()
Subscribe Infeepedia youtube channel for computer science competitive exams
Download Infeepedia app and call or wapp on 8004391758
OOPs Infeepedia By: Infee Tripathi
this.color = color; }
this.price = price; void display()
} {
void display() cout << "Model: " << model << ", Color:
{ " << color << ", Price: " << price <<
System.out.println("Model: " + model + endl;
", Color: " + color + ", Price: " + price); }
} };
} int main()
public class Main {
{ Car c1; // Default arguments used Car
public static void main(String[] args) c2("Swift", "Red", 500); // Explicit
{ arguments override defaults
Car c1 = new Car(); // Default c1.display();
constructor c2.display();
Car c2 = new Car("Swift", "Red", 500); return 0;
// Parameterized constructor }
c1.display();
c2.display();
}}

3. Copy constructor
 It is used to copy one object’s value to another object of the same class.
 A copy constructor is used to initialize an object using another object of the same class.

In C++:
 If we don't define a copy constructor explicitly, the compiler creates one implicitly. Even if we define other constructors,
the compiler will always create an implicit copy constructor unless we specifically provide one.
 This behaviour is unlike the default constructor, where if you define any constructor explicitly, the default constructor is
deleted.
Syntax for explicit copy constructor:
It takes a reference to an object of the same class as an argument.
ClassName (ClassName &obj)
{
// body_containing_logic
}

In Java:
 Java does not have explicit copy constructors. Instead, cloning is used.
 The clone() method from the Object class is used, and the class must implement the Cloneable interface.

In Python:
 Python does not have explicit copy constructors. Copying is handled using the copy module.
 Shallow copy (copy.copy()) and deep copy (copy.deepcopy()) are available.

Use of copy constructor:-


Constructs a new object by copying values from an existing object.
Can be used to perform deep copy.
Modify specific attributes during the copy process if needed.

Subscribe Infeepedia youtube channel for computer science competitive exams


Download Infeepedia app and call or wapp on 8004391758
OOPs Infeepedia By: Infee Tripathi
Destructor

Destructors in C++:
 C++ supports destructors, and they are essential for managing dynamic memory and other resources.
 A destructor is a special member function used to destroy the objects created by constructor. It cleans up memory and
release resources held by objects.
 A destructor has the same name as the class, but it is preceded by a tilde (~) symbol.
 Only one destructor is allowed per class.
 Destructors don't take any arguments and don't return any value therefore it cannot be overloaded
 Destructor cannot be declared as static and const;
 Destructor should be declared in the public section of the program.
 When an object goes out of scope or is explicitly deleted, its destructor is automatically called by the compiler.
 Destructors are executed in the reverse order of the constructors. This ensures that resources are released in the opposite
order of their allocation.
 Like constructors, destructors can also be defined either inside or outside of the class.

The syntax for defining the destructor within the class


~ <class-name>(){}

The syntax for defining the destructor outside the class


<class-name>: : ~<class-name>() {}

Destructors in Java:
 Java does not have explicit destructors because it relies on garbage collection to automatically manage memory. However,
a method called finalize() was historically used for cleanup, but it is now deprecated.
 Use try-with-resources or implement the AutoCloseable interface for resource cleanup.
 Explicit cleanup can be done using custom methods.

Destructors in Python:
 Python uses a special method __del__() to act as a destructor. However, since Python relies on garbage collection,
destructors are rarely needed.
 __del__() is called when an object is deleted or goes out of scope.
 Use with caution as garbage collection may delay its execution.

Java CPP Python


class Car { #include <iostream> class Car:
Car() using namespace std; def __init__(self):
{ System.out.println("Constructor print("Constructor called")
called"); } class Car {
// Explicit cleanup method public: def __del__(self):
void cleanup() { Car() { print("Destructor called")
System.out.println("Cleanup cout << "Constructor called\n";
called"); } c1 = Car() # Constructor is called
}} ~Car() { del c1 # Destructor is called
public class Main cout << "Destructor called\n";
{ } };
public static void main(String[] args) int main() {
{ Car c1 = new Car(); Car c1; // Constructor is called
c1.cleanup(); // Explicit cleanup return 0; // Destructor is
} } automatically called }

Subscribe Infeepedia youtube channel for computer science competitive exams


Download Infeepedia app and call or wapp on 8004391758
OOPs Infeepedia By: Infee Tripathi
Access Specifiers
 To implement Data Hiding or encapsulation which is the most important concept of the oops, we use access specifiers or
modifier.
 Access Specifiers in a class decide the accessibility of the class members(data and function) in other classes.
 Specifiers decide whether the class members will get directly accessed by the blocks present outside the class or not,
 By default, all members in a class are private in C++ and Java, but in Python, they are public by default (with naming
conventions to mimic private or protected behavior).
 In Python, access control is implemented using naming conventions:
 _protectedMember: Protected
 __privateMember: Private

There are three types of access modifiers in OOPS:


1. Public
2. Private
3. Protected

1. Public: If any class member (data members/member functions) is declared as public then:–
1. They are accessible to everyone.
2. They can be accessed using the direct member access operator (.).

2. Private: If any class member is declared as private then:


 It can only be accessed by functions declared inside the class
 It is not accessible from the outside of class
 Only the member functions(in C++, jave ,python) or the friend functions/classes(only in C++) are allowed to access the
private data members of a class.
 If no specifier is mentioned then by default the class members are private (in C++ and java not in python).
 In Python, private members are indicated using a double underscore prefix (__privateVar).
 We can access the private data members of a class indirectly
 By creating getter/setter functions
 By initializing values via constructors
 By setting values via public function

Java CPP Python


class Example class Example class Example:
{ { def __init__(self):
private private: int privateVar; self.__privateVar = 0 # Private variable
int privateVar; // Setter
// Setter public: void setVar(int value) # Setter
public void setVar(int value) { privateVar = value; } def setVar(self, value):
{ privateVar = value; } // Getter
// Getter int getVar() # Getter
public int getVar() { self.__privateVar = value
{ return privateVar; } } return privateVar; def getVar(self):
public class Main } return self.__privateVar
{ };
public static void main(String[] args) int main() obj = Example()
{ { obj.setVar(10) # Indirect access
Example obj = new Example(); Example obj; print(obj.getVar()) # Indirect access
obj.setVar(10); // Indirect access obj.setVar(10); // Indirect access
System.out.println(obj.getVar()); cout << obj.getVar(); // Indirect access
// Indirect access } } }

Subscribe Infeepedia youtube channel for computer science competitive exams


Download Infeepedia app and call or wapp on 8004391758
OOPs Infeepedia By: Infee Tripathi
3. Protected: If any class members are declared as protected then:-
 It is the same as private accessibility.But, derived (subclasses/child) classes can also access the protected class
members.
 The main difference between private and protected is that protected inheritance allows continued access to base class
members whereas private inheritance prohibits the access of those members.
 These protected members are inaccessible outside. But, are accessible in the derived class as protected data members.
 In C++, the access level of protected members in the derived class depends on the inheritance mode:
 Public Inheritance: Protected remains protected.
 Protected Inheritance: Protected remains protected.
 Private Inheritance: Protected becomes private.
 In Java, protected members are accessible in the same package and through inheritance in other packages.
 In Python, protected members are indicated with a single underscore (_protectedVar) and can be accessed in
subclasses.
Note: This access through inheritance can alter the access modifier of the elements of base class in derived class depending
on the mode of Inheritance.

Specifier Within Same Class In Derived Class Outside the Class


Private Yes No No
Protected Yes Yes No
Public Yes Yes Yes

Java CPP Python


class Base class Base class Base:
{ { def __init__(self):
protected int protectedVar; protected: self._protectedVar = 0 # Protected
} int protectedVar; variable
class Derived extends Base };
{ class Derived : public Base { class Derived(Base):
public void setVar(int value) public: def setVar(self, value):
{ void setVar(int value) self._protectedVar = value #
protectedVar = value; { Accessible in derived class
} protectedVar = value;
// Accessible in derived class } def getVar(self):
public int getVar() // Accessible in derived class return self._protectedVar
{ int getVar()
return protectedVar; { obj = Derived()
} return protectedVar; obj.setVar(10) # Indirect access
} } }; print(obj.getVar())
public class Main Int main()
{ {
public static void main(String[] args) Derived obj;
{ obj.setVar(10); // Indirect access
Derived obj = new Derived(); cout << obj.getVar();
obj.setVar(10); // Indirect access }
System.out.println(obj.getVar());
}}

Subscribe Infeepedia youtube channel for computer science competitive exams


Download Infeepedia app and call or wapp on 8004391758
OOPs Infeepedia By: Infee Tripathi
Encapsulation
 Encapsulation bundles data (variables) and methods (functions) into a single unit, called a class.
 It prevents direct access to data, allowing it to be accessed or modified only through specific methods.
 Works like a "locked box," where only authorized methods (keys) can access or
change the data.
 Ensures data protection and hiding, keeping the code organized, secure, and easier
to manage.
 Implemented using access specifiers: public, private, and protected.
 Improves readability, maintainability, and security by controlling how data is
accessed or modified.
 Supports read-only mode (data can be accessed but not modified) and write-only mode (data can be modified
but not accessed).

Java CPP Python


class Car class car { class Car:
{ private: def __init__(self):
private String name; string name; self.__name = None # Private
private int mNumber; int m_number; attribute
public String color; public: self.__m_number = None # Private
string color; attribute
// Method to set data void setdata(string s1,int m1) self.color = None # Public attribute
public void setData(String s1, int m1) {
{ name = s1; mNumber = m1; } name = s1; # Method to set data
m_number = m1; def set_data(self, name, m_number):
// Method to get data public } self.__name = name
void getData() { void getdata() self.__m_number = m_number
System.out.println("Name is: " + name); { cout<<"Name is: " <<name<<endl;
System.out.println("m_number is: " + # Method to get data def
mNumber); cout<<"m_number is: "<<m_number<< get_data(self):
} endl; print(f"Name is: {self.__name}")
} } }; print(f"m_number is:
public class Main { public static void int main() {self.__m_number}")
main(String[] args) {
{ car c; # Main program
Car c = new Car(); c.color= “red”; c = Car()
c.color = "red"; c.setdata("Alto", 102); c.color = "red"
c.setData("Alto", 102); c.getdata(); c.set_data("Alto", 102)
c.getData(); cout<<"Color is: " <<color<<endl; c.get_data()
System.out.println("Color is: " + c.color); } return 0; print(f"Color is: {c.color}")
} }

Types of Encapsulation
We can implement encapsulation in three ways:
1. Member variable encapsulation
2. Function encapsulation
3. Class encapsulation

1. Data Encapsulation
 Data members (variables) are declared private to restrict direct access.
 Access to these variables is provided through public getter and setter methods.
 Ensures controlled access and modification of data.
Subscribe Infeepedia youtube channel for computer science competitive exams
Download Infeepedia app and call or wapp on 8004391758
OOPs Infeepedia By: Infee Tripathi
Example:
 C++/Java: Use private keyword and define getter/setter functions.
 Python: Use double underscore __ for private variables and define methods for access.

Java CPP Python


class Car #include<iostream> class Car:
{ using namespace std; def __init__(self):
private String name; class car { self.__name = "" # Private variable
// Setter method private:
public void setData(String s1) string name; # Setter method def
{ name = s1; } public: set_data(self, name):
// Getter method void setdata(string s1) self.__name = name
public void getData() {
{ System.out.println("Name is: " + name=s1; # Getter method
name); } def get_data(self):
} void getdata() { print(f"Name is: {self.__name}")
public static void main(String[] args) cout << "Name is: "<<name<<endl;
{ Car c = new Car(); } }; # Main function
c.setData("Alto"); int main() { if __name__ == "__main__":
c.getData(); car c; c = Car()
} c.setdata("Alto"); c.set_data("Alto")
} c.getdata(); return 0; } c.get_data()

2. Function Encapsulation
 Hides the internal logic of a method from the user.
 Only the required functionality is exposed via public methods.
 Internal details can be modified without affecting external code.
 In Java and C++, private methods are defined using the private keyword, and public methods are accessible
outside the class.
 In Python, private methods are defined with a double underscore prefix (e.g., __speed_calculate), making them
inaccessible directly outside the class.

Java CPP Python


class Car { using namespace std; class Car:
private void speedCalculate() class car { def __init__(self):
{ private: self.name = ""
int speed; void speedcalculate() { self.m_number = 0
if (mNumber > 200 && year > 2020) int speed; self.year = 0 # Private method
{ speed = 150; if(m_number>200 && year>2020) { def __speed_calculate(self):
System.out.println("Speed is " + speed= 150; if self.m_number > 200 and self.year >
speed); } cout<< "speed is "<< speed<<endl; 2020:
else { } speed = 150
speed = 100; else { speed=100; print(f"Speed is {speed}")
System.out.println("Speed is " + cout<< "speed is "<< speed<<endl; } } else:
speed); } } public: speed = 100
public String name; string name; print(f"Speed is {speed}")
public int mNumber; int m_number; def get_speed(self):
public int year; int year; self.m_number = 300
public void getSpeed() void getspeed() { self.year = 2021
{ mNumber = 300; m_number=300; self.__speed_calculate()
year = 2021; year=2021; # Main function

Subscribe Infeepedia youtube channel for computer science competitive exams


Download Infeepedia app and call or wapp on 8004391758
OOPs Infeepedia By: Infee Tripathi
speedCalculate(); } speedcalculate(); } }; if __name__ == "__main__":
public static void main(String[] args) int main() { c = Car()
{ Car c = new Car(); car c; c.get_speed()
c.getSpeed(); c.getspeed();
}} return 0; }

3. Class Encapsulation
 Combines data members and methods into a single unit (class).
 Prevents external interference and enforces data hiding.
Nested Class:
 In Java.C++,Python, a nested class is created using the class keyword inside another class.
 Nested classes in C++ can be made friend to the enclosing class or other classes for special access.
Access:
 In Java, the nested class instance is created using new and accessed directly.
 In Python, the nested class instance is created using self and accessed via methods.

Java Python C++


class Student { #include<iostream> python
private class Address { using namespace std; Copy code
private String street, city, state, class student { class Student:
zipcode; private: class Address:
public void getAddress() { class Address { def __init__(self):
street = "123 street"; private: self.street = ""
city = "Kanpur"; string street, city, state, zipcode; self.city = ""
state = "UP"; public: self.state = ""
zipcode = "211210"; string getaddress() self.zipcode = ""
System.out.println("Address is " + {
street + " " + city + " " + state + " " + street = "123 street"; def get_address(self):
zipcode); city = "Kanpur"; self.street = "123 street"
} } state = "UP"; self.city = "Kanpur"
private Address a = new Address(); zipcode = "211210"; self.state = "UP"
cout<< "Address is "<<street <<" "<< city << self.zipcode = "211210"
public void myAddress() { "" print(f"Address is
a.getAddress(); << state <<" "<< zipcode << endl; {self.street} {self.city} {self.state}
} return 0; } }; {self.zipcode}")
public static void main(String[] args) { Address a;
Student s = new Student(); public: def __init__(self):
s.myAddress(); void myaddress() { self.a = self.Address()
} a.getaddress();
} }}; def my_address(self):
int main() { self.a.get_address()
student s;
s.myaddress(); if __name__ == "__main__":
return 0; s = Student()
} s.my_address()

Subscribe Infeepedia youtube channel for computer science competitive exams


Download Infeepedia app and call or wapp on 8004391758
OOPs Infeepedia By: Infee Tripathi
Inheritance
 In terms of programming it is a capability of class (child) to derive data and behaviour of another class (parent) which
increases code reusability and reduce code size and redundancy.
 The class whose properties are acquired is called super parent/base class.
 The class which acquire all the properties is called derived /sub/child class.

Need of inheritance

Class Vehicle
Name, color,model_number
Start(), stop(), applybrake()

Class erikshaw
Name, color,model_number
Class bike Start(), stop(), applybrake()
Name, color,model_number Charge()
Start(), stop(), applybrake()
Halmetholder()
Class car
Name, color,model_number
Start(), stop(), applybrake()
Reverse()

Mode of inheritance
There are three modes of inheritance:

Base class Mode Inheritance mode


Of access specifiers Public Protected Private
Public Public Protected Private
Protected Protected Protected Private
Private Not accessible Not accessible Not accessible

Syntax of inheritance in Java, C++ and Python

Java Cpp Python


class BaseClass class BaseClass class BaseClass:
{ { # Base class members
// Base class members // Base class members pass
} };
class DerivedClass extends BaseClass class DerivedClass : public BaseClass class DerivedClass(BaseClass):
{ { # Derived class members
//Derived class members // Derived class members pass
} };

Subscribe Infeepedia youtube channel for computer science competitive exams


Download Infeepedia app and call or wapp on 8004391758
OOPs Infeepedia By: Infee Tripathi
Aspect C++ Java Python
Keyword : public extends Parent class in parentheses
Access Specifiers public, protected, No explicit keyword; default is No explicit keyword; uses naming
private protected conventions
Multiple Supported directly Not supported (uses interfaces) Supported directly
Inheritance
Code Style Explicit and verbose More concise than C++ Simplest and most concise

Types of Inheritance
There are five types of inheritance:
1. Single Inheritance
2. Multiple Inheritance
3. Multilevel Inheritance
4. Hierarchical Inheritance
5. Hybrid Inheritance

1. Single Inheritance
When the derived class inherits the properties of only one base class, it is called as Single Inheritance.
It is used to reuse, extend or modify the behavior of the parent class.

A(base class)

B(Derived class)

class Vehicle { String name; void start() #include<iostream> class Vehicle:


{ using namespace std; def __init__(self):
System.out.println("Vehicle started"); class vehicle self.name = ""
System.out.println("Name is " + name); } { public:
void stop() string name; def start(self):
{ void start() print("Vehicle started")
System.out.println("Vehicle stopped"); { print(f"Name is {self.name}")
}} cout<< "vehicle started "<< endl; def stop(self):
class Car extends Vehicle cout<< "name is " << name<< endl; print("Vehicle stopped")
{ }
int wheels; void stop() class Car(Vehicle):
void reverse() { cout<< "vehicle stopped " << endl; def __init__(self):
{ } }; super().__init__()
System.out.println("Car is in back gear."); class car: public vehicle self.wheels = 0
}} {
public class Main public: def reverse(self):
{ int wheels; print("Car is in back gear.")
public static void main(String[] args) void reverse() c = Car()
{ { cout<< "car is in back gear. "<< endl; c.name = "WagonR"
Car c = new Car(); } }; c.start()
c.name = "WagonR"; int main() c.stop()
c.start(); { car c; c.reverse()
c.stop(); c.name="WagonR";
c.reverse(); c.start();
}} c.stop();
c.reverse(); }

Subscribe Infeepedia youtube channel for computer science competitive exams


Download Infeepedia app and call or wapp on 8004391758
OOPs Infeepedia By: Infee Tripathi
Output:-
vehicle started
name is WagonR
vehicle stopped
car is in back gear.
Multiple Inheritance
When a derived /child/sub class inherits the properties of more than one base/parent/super class, it is called multiple
inheritance.
A(base class) B(base class)

C(Derived class)

Java CPP Python


interface Electronics #include<iostream> class Electronics:
{ using namespace std; def __init__(self):
void on(); class Electronics { self.range = None
void off(); public:
} string range; def on(self):
interface Mechanical void on() print("On button is pressed")
{ { print(f"Access range is {self.range}")
void pushed(); cout<< "on button is pressed "<<
} endl; def off(self):
class Car implements Electronics, cout<< "access range is " << range<< print("Off button is pressed")
Mechanical endl;
{ } class Mechanical:
String range; void off() def __init__(self):
String weight; { self.weight = None
int wheels; cout<< "off button is pressed" <<
public void on() endl; def pushed(self):
{ } }; print("Push button is pressed")
System.out.println("On button is class mechanical print(f"Weight is {self.weight}")
pressed"); {
System.out.println("Access range is " + public: class Car(Electronics, Mechanical):
range); string weight; def __init__(self):
} void pushed() Electronics.__init__(self)
public void off() { Mechanical.__init__(self)
{ cout<< " push button is pressed "<< self.wheels = None
System.out.println("Off button is endl;
pressed"); cout<< "weight is " << weight<< endl; def reverse(self):
} } }; print("Car is in back gear.")
public void pushed()
{ class car: public Electronics, public # Main program
System.out.println("Push button is mechanical c = Car()
pressed"); { c.range = "10 mtr"
System.out.println("Weight is " + public: c.weight = "300kg"
weight); int wheels; c.on()
} void reverse() c.pushed()
public void reverse() { c.reverse()
{ cout<< "car is in back gear. "<< endl;
} };
Subscribe Infeepedia youtube channel for computer science competitive exams
Download Infeepedia app and call or wapp on 8004391758
OOPs Infeepedia By: Infee Tripathi
System.out.println("Car is in back gear."); int main()
} {
public static void main(String[] args) car c;
{ c.range="10 mtr";
Car c = new Car(); c.weight= "300kg";
c.range = "10 mtr"; c.on();
c.weight = "300kg"; c.pushed();
c.on(); c.reverse();
c.pushed(); }
c.reverse();
}
}

Output:-
On button is pressed
Access range is 10 mtr
Push button is pressed
Weight is 300kg
car is in back gear.

Feature C++ Java Python


Multiple Supported directly Supported via interfaces Supported directly
Inheritance
Syntax class Car : public Class1, public class Car implements Interface1, class Car(Class1, Class2)
Class2 Interface2
Ease of Use Verbose Requires interface implementation Simplest and direct
Initialization Implicit for parent classes Explicit in interfaces Explicit for all parent
classes

Diamond Problem
 Suppose A’s properties are inherited by B and C classes and then D inherits the properties of both B and C, as this
situation is creating a diamond shape, therefore, this problem is known as “diamond problem”.
 In this situation classes B and C both can access the properties of A.
 D can access the properties of B and C. So D can access A via B and via C.
 This causes ambiguity. As the compiler will get confused.
 In C++, the diamond problem is handled using virtual inheritance to avoid
ambiguity.
 In Java, the diamond problem does not occur because multiple inheritance
with classes is not allowed. Instead, Java uses interfaces to achieve multiple
inheritance, which avoids ambiguity since interfaces do not have
implementations.
 In Python, the diamond problem is resolved using the Method Resolution Order (MRO), which follows the C3
Linearization Algorithm. Python ensures that each class in the hierarchy is called only once.
Feature C++ Java Python
Occurrence Yes, in multiple inheritance No, as Java does not support multiple Yes, but resolved using MRO
inheritance with classes
Resolution Virtual inheritance Interfaces (no implementation conflict) C3 Linearization (MRO)
Ambiguity Can occur without virtual Not possible Automatically resolved
inheritance
Ease of Requires explicit virtual No special handling required No special handling required
Handling inheritance

Subscribe Infeepedia youtube channel for computer science competitive exams


Download Infeepedia app and call or wapp on 8004391758
OOPs Infeepedia By: Infee Tripathi
Multilevel Inheritance
When a derived class inherits the properties of the base class and further it become the base class(parent class) to the other
class (or further it’s property is inherited by some other class), it is called Multilevel Inheritance.
There can be any number of levels i.e any number of derived classes in multilevel inheritance. The chain of inheritance can
extend to multiple levels, allowing classes to inherit properties and behaviors from their ancestors.

A(base
class)
B(Derived class/base class for C)

C(Derived
class)
Java CPP Python
class Vehicle class vehicle class Vehicle:
{ { def __init__(self):
String name; public: self.name = ""
void start() string name;
{ void start() def start(self):
System.out.println("Vehicle started"); { print("Vehicle started")
System.out.println("Name is " + cout<< "vehicle started "<< endl; print(f"Name is {self.name}")
name); cout<< "name is " << name<< endl;
} } def stop(self):
void stop() void stop() print("Vehicle stopped")
{ { class Car(Vehicle):
System.out.println("Vehicle stopped"); cout<< "vehicle stopped " << endl;
}} } }; def __init__(self):
class Car extends Vehicle class car: public vehicle super().__init__()
{ { self.wheels = 0
int wheels; public:
void reverse() int wheels; def reverse(self):
{ void reverse() print("Car is in back gear.")
System.out.println("Car is in back { class MarutiSuzuki(Car):
gear."); } } cout<< "car is in back gear. "<< endl;
class MarutiSuzuki extends Car } }; def __init__(self):
{ class maruti_suzuki: public car super().__init__()
int mNumber; { public: self.m_number = 0
void print(int x) int m_number;
{ mNumber = x; void print(int x) def print_model(self, x):
System.out.println("Model number is { m_number =x; self.m_number = x
" + mNumber); cout<< "model number is " print(f"Model number is
}} <<m_number<<endl; {self.m_number}")
public class Main { }
public static void main(String[] args) }; # Main code
{ int main() m = MarutiSuzuki()
MarutiSuzuki m = new MarutiSuzuki(); { m.name = "WagonR"
m.name = "WagonR"; maruti_suzuki m; m.start()
m.start(); m.name="WagonR"; m.stop()
m.stop(); m.start(); m.reverse()
m.reverse(); m.stop(); m.print_model(193)
m.print(193); m.reverse();
}} m.print(193); }
Subscribe Infeepedia youtube channel for computer science competitive exams
Download Infeepedia app and call or wapp on 8004391758
OOPs Infeepedia By: Infee Tripathi
Output:-
Vehicle started
Name is WagonR
Vehicle stopped
car is in back gear.
Model number is 193.

Aspect C++ Java Python


Inheritance class Derived : public class Derived extends Base class Derived(Base)
Syntax Base
Access Public, Private, Public, Private, Protected (default for No explicit specifiers; everything is
Specifiers Protected members is package-private) public by default
Constructors Must be explicitly Uses super() to call parent constructor Uses super().__init__() to call
defined and called parent constructor

Hierarchical Inheritance
When more than one derived class inherit the properties of single base class, it is called Hierarchical Inheritance.

A(base class)

B(derived class) C(Derived class)

D(derived class) E(derived class)

Java C++ Python


class Vehicle { class vehicle class Vehicle:
String name; { def __init__(self, name=""):
void start() public: self.name = name
{ string name;
System.out.println(name + " is void start() def start(self):
started"); { print(f"{self.name} is started")
} cout<< name <<" is started "<< endl;
void stop() { } def stop(self):
System.out.println(name + " is void stop() print(f"{self.name} is stopped")
stopped"); {
} cout<< name <<" is stopped "<< endl;
} } }; class Car(Vehicle):
class Car extends Vehicle { class car: public vehicle def __init__(self, name="",
int wheels; { public: wheels=4):
int wheels; super().__init__(name)
void reverse() { void reverse() self.wheels = wheels
System.out.println("Car is in back { out<<"car is in back gear."<< endl;
gear."); } }; def reverse(self):
} class bike: public vehicle print("Car is in back gear.")
} { public:
class Bike extends Vehicle { string type; class Bike(Vehicle):
String type; void halmetholder() def __init__(self, name="",
void helmetHolder() { { bike_type=""):
System.out.println("This is a " + cout<< "this is a "<< type<< "bike" super().__init__(name)
type + " bike"); <<endl; self.type = bike_type
Subscribe Infeepedia youtube channel for computer science competitive exams
Download Infeepedia app and call or wapp on 8004391758
OOPs Infeepedia By: Infee Tripathi
System.out.println("Helmet holder cout<< "halmet holder is opened" <<
is opened"); endl; def helmet_holder(self):
} } }; print(f"This is a {self.type} bike")
} int main() print("Helmet holder is opened")
public class Main { {
public static void main(String[] args) { car c;
Car c = new Car(); bike b; # Main Code
Bike b = new Bike(); c.name="WagonR"; c = Car(name="WagonR")
c.name = "WagonR"; b.name="pulser"; b = Bike(name="Pulsar",
b.name = "Pulsar"; c.start(); bike_type="sports")
c.start(); b.stop();
b.stop(); c.reverse(); c.start()
c.reverse(); } b.stop()
b.type = "sports"; c.reverse()
b.helmetHolder(); b.helmet_holder()
}
}

Output:-
WagonR is started
pulser is stopped
car is in back gear.

Aspect C++ Java Python


Constructor Not mandatory, but can Uses default or parameterized Uses __init__ method for initialization
initialize manually constructors
Access Public, Private, Protected Public, Protected, Private No explicit access modifiers;
Modifiers (default: package-private) attributes are public by default
Inheritance class Derived : public Base class Derived extends Base class Derived(Base)
Syntax

Hybrid inheritance
It is a combination of one or more types of inheritance.

A(base class) A(base class)

B(derived class) C(Derived class)

D(derived class) E(derived class)

Subscribe Infeepedia youtube channel for computer science competitive exams


Download Infeepedia app and call or wapp on 8004391758
OOPs Infeepedia By: Infee Tripathi
class World #include<iostream> class World:
{ using namespace std; def __init__(self):
World() class World { print("We are in World!")
{ System.out.println("We are in public:
World!"); World() { # Single Inheritance
}} cout << "we are in World!"<< endl; class Continent(World):
} }; def __init__(self):
// Single Inheritance // Single Inheritance. super().__init__()
class Continent extends World class Continent: public World { print("We are in Continent")
{ public: class Country:
Continent() Continent() { def __init__(self):
{ cout << "We are in Continent\n"; print("We are in Country")
System.out.println("We are in }
Continent"); }; # Multiple Inheritance
}} class Country { class India(Continent, Country):
public: def __init__(self):
class Country Country() { Continent.__init__(self)
{ cout << "We are in Country"<<endl;
Country() } }; # Explicitly call Continent's constructor
{ // multiple Inheritance. Country.__init__(self)
System.out.println("We are in class India: public Continent, public
Country"); Country { # Explicitly call Country's constructor
}} public: print("We are in India!")
India() {
// Multiple Inheritance Simulation cout << "We are in India!"; # Main Code
using Interfaces } }; I = India()
class India extends Continent int main() {
{ Country country = new Country(); India I;
// Simulate multiple inheritance }
India()
{ System.out.println("We are in
India!"); } }
public class Main
{
public static void main(String[] args)
{
India I = new India();
}
}

Output:-
we are in World!
We are in Continent
We are in Country
We are in India!

Subscribe Infeepedia youtube channel for computer science competitive exams


Download Infeepedia app and call or wapp on 8004391758
OOPs Infeepedia By: Infee Tripathi
Polymorphism
Polymorphism = "poly" + "morphs" = many forms.
In real life a person can play different role in like a lady can be mom, daughter, wife, teacher etc.

Types of Polymorphism
1. Compile time polymorphism
a) Function Overloading
b) Operator Overloading(not in java)

2. Run time polymorphism


a) Function overriding

Compile time polymorphism


 This type of polymorphism is achieved by function overloading or operator overloading (only in C++).
 Information about overloading (type, argument etc) is
known prior so we can check it at the time of program
compilation.
 Here compiler selects the appropriate function to run
at compile time.
 It is also known as static binding or early binding.
 In Java only supports method overloading (no operator
overloading).
 In Python function overloading does not directly Function Overriding
supported but simulates it using default arguments
and operator overloading is supported via magic methods.

Method Overloading
 In Method overloading more than one method is having the same name but with the different number of parameters or
the type of the parameters or order of the parameters.
 The compiler determines which function to call based on the number, type, and order of arguments passed during the
function call.
 In Python not directly supported like in C++ or Java. But achieved using Default arguments and Variable-length
arguments.

Example:
class Calculator class Calculator class Calculator:
{ { def add(self, a, b, c=0):
// Two integers // Two integers return a + b + c
public: int add(int a, int b) int add(int a, int b) # Handles two or three arguments
{ return a + b; } { return a + b; }
// Two doubles
double add(double a, double b) // Two doubles
{ double add(double a, double b)
return a + b; { return a + b; }
}
// Three integers // Three integers
int add(int a, int b, int c) int add(int a, int b, int c)
{ return a + b + c; } { return a + b + c; }
}; }

Subscribe Infeepedia youtube channel for computer science competitive exams


Download Infeepedia app and call or wapp on 8004391758
OOPs Infeepedia By: Infee Tripathi
Feature C++ Java Python
Function Overloading Fully supported Fully supported Simulated using defaults or
*args
Key Differentiators Number, type, order of Number, type, order of Default or variable-length
params params params
Compile-Time Yes Yes No, runtime evaluation
Binding

Operator Overloading
 By using operator overloading we can play with operators.
 It allows us to create operators that can serve specific purposes with user-defined functions.
 In operator overloading, different operators display different implementations based on their parameters or signatures.
 Suppose + operator work as the minus one.
 We use keyword “operator” (in C++ only ) along with the operator symbol that we want to overload.
 These operator functions get invoked when their corresponding operators are used in the program.
 We can overload almost all operators except

Operators That Can Be Overloaded:


 Arithmetic operators : - , + , / , * , % and -=, +=, /= , *= , %=
 Relational Operators : !=, ==, > ,< ,>=, <=
 Bitwise operators : &, |, ^ ,<< ,>> and |=, &= ,>>=, <<=, ^=
 Logical operators: && ,||
 Memory management : new[], new, delete[], delete

Operators That Cannot Be Overloaded:


.(dot operator), :: (scope operator), ?: (ternary operator), size of operator, “.*” and typeid.

Feature C++ Java Python


Operator Overloading Fully supported using operator Not directly supported Supported via dunder methods
Syntax ClassName operator+ Use method like add() Define __add__, __sub__, etc.
Flexibility High Simulated through methods High
Ease of Use Moderate Easy Easy

C++: Templates
 C++ templates allow the creation of generic functions and classes that can work with any data type.
 The template keyword is used to define templates.
 Function Templates: Create functions that work with any data type.
 Class Templates: Create classes that work with any data type.
 They allow for compile-time instantiation of code based on different data types, facilitating compile-time polymorphism
by generating specific code for each data type at compile time.
Syntax:
template <typename T>
T functionName(T param) {
// Function body
}

Subscribe Infeepedia youtube channel for computer science competitive exams


Download Infeepedia app and call or wapp on 8004391758
OOPs Infeepedia By: Infee Tripathi
Java: Generics
 Java uses generics to achieve the same functionality as templates.
 Generics ensure type safety and are checked at compile time.
 Generics can be used with classes, methods, and interfaces.
 Java generics are implemented using type erasure, meaning type information is erased at runtime.
Syntax:
class ClassName<T> {
// Generic class body
}
public <T> T methodName(T param) {
// Generic method body
}

Python: Generics
 Python achieves generic programming through duck typing and the typing module.
 Python is dynamically typed, so generics are not enforced at runtime but are used for type hinting and static type
checking.
 The typing module provides support for generics using TypeVar and generic classes.
 Python functions and classes are inherently generic due to its dynamic nature.
Syntax:
from typing import TypeVar, Generic
T = TypeVar('T')
class ClassName(Generic[T]):
# Generic class body

Runtime Polymorphism
 Run time polymorphism is achieved by method overriding where two or more functions with the same name, arguments,
and return type base and derived classes. The base class is called overridden.
 This method has a comparatively slower execution rate than compiletime polymorphism since all the methods that need
to be executed are called during run time.
 It is also called Late binding and dynamic polymorphism.
 Runtime polymorphism occurs when a function in a base class is overridden in a derived class, and the appropriate
function is called at runtime based on the object's type.
 The base class function is marked as virtual in C++ or overridden using the @Override annotation in Java.
 In Python, method overriding is directly supported without additional keywords.
 A base class pointer/reference is used to call the derived class function at runtime.
 In C++ Use the virtual keyword in the base class for the function to allow overriding.

Function overriding

Java CPP Python


class Vehicle #include <iostream> using namespace class Vehicle:
{ std;
void start() class Vehicle def start(self):
{ { public: print("Vehicle started")
System.out.println("Vehicle started"); virtual void start()
}} { class Car(Vehicle):
class Car extends Vehicle cout << "Vehicle started" << endl; def start(self):
{ } }; print("Car started")
@Override class Car : public Vehicle
void start() { v = Car() # Derived class object

Subscribe Infeepedia youtube channel for computer science competitive exams


Download Infeepedia app and call or wapp on 8004391758
OOPs Infeepedia By: Infee Tripathi
{ public: void start() override v.start() # Calls Car's start() at
System.out.println("Car started"); { runtime
}} cout << "Car started" << endl; } };
public class Main { public static void int main()
main(String[] args) { Vehicle* v = new Car();
{ // Base class pointer to derived class
Vehicle v = new Car(); object
// Base class reference to derived v->start();
class object // Calls Car's start() at runtime
v.start(); delete v;
// Calls Car's start() at runtime return 0;
}} }

Comparison between C++, Java and Python


Feature C++ Java Python
Keyword for Overriding virtual and override @Override annotation No special keyword needed
Function Resolution Virtual table (vtable) Dynamic method dispatch Direct method overriding
Ease of Use Moderate Easy Very easy
Base Class Reference Required for polymorphism Required for polymorphism Optional

Normal Programs with function overriding


Java CPP Python
class Car { #include <iostream> class Car:
public void display() { using namespace std; def display(self):
System.out.println("Basic car has class car print("Basic car has manual
manual functions"); { functions")
}} public:
class BMW extends Car { void display() class BMW(Car):
@Override { def display(self):
public void display() { cout << "Basic car has manual print("BMW has automatic
System.out.println("BMW has functions" <<endl; functions")
automatic functions"); }
}} }; # Main function
public class Main { class BMW: public car if __name__ == "__main__":
public static void main(String[] args) { { c = Car()
Car c = new Car(); public: b = BMW()
BMW b = new BMW(); void display() c.display() # Calls the display
c.display(); // Calls the display { cout << "BMW has automatic method of Car
method of the Car class functions" <<endl; b.display() # Calls the overridden
b.display(); // Calls the overridden } }; display method of BMW
display method of the BMW class int main()
} { car c;
} BMW b;
c.display();
b.display(); }
Output:
Basic car has manual functions
BMW has automatic functions

Subscribe Infeepedia youtube channel for computer science competitive exams


Download Infeepedia app and call or wapp on 8004391758
OOPs Infeepedia By: Infee Tripathi
Program of function overriding with Base class reference pointing to a derived class object
class Car { #include <iostream> class Car:
public void display() { using namespace std; def display(self):
System.out.println("Basic car has class car print("Basic car has manual
manual functions"); { functions")
} public:
} void display() class BMW(Car):
class BMW extends Car { { def display(self):
@Override cout << "Basic car has manual print("BMW has automatic
public void display() { functions"<<endl; functions")
System.out.println("BMW has } };
automatic functions"); class BMW: public car # Main function
} } { if __name__ == "__main__":
public class Main { public: c = BMW() # Creating an instance of
public static void main(String[] args) { void display() BMW and assigning it to a variable of
Car c = new BMW(); // Polymorphism: { type Car
Base class reference pointing to a cout << "BMW has automatic c.display() # Calls the overridden
derived class object functions" <<endl; } }; display method of BMW
c.display(); // Calls the overridden int main()
method in the BMW class { car *c = new BMW();
} } c->display(); }
Output:
BMW has automatic functions
Program of overridden method in the derived class

Java CPP Python


class Car { #include <iostream> class Car:
public void print() using namespace std; def print(self):
{ System.out.println("This is a basic class car { print("This is a basic car")
car"); } public:
public void show() void print() def show(self):
{ { cout << "This is a basic car "<<endl; } print("Manual car features")
System.out.println("Manual car virtual void show()
features"); { cout << "Mannual car features"<<endl; } class BMW(Car):
}} }; def print(self):
class BMW extends Car class BMW : public car { print("This is an advanced car")
{ public:
@Override void print() def show(self):
public void print() { cout << "This is an advance car"<<endl; } print("Automatic car features")
{ void show()
System.out.println("This is an { # Main function
advanced car"); cout << "Automatic car features"<<endl; } if __name__ == "__main__":
} }; c = BMW() # Creating an instance of
@Override int main() BMW
public void show() { c.print() # Calls the overridden print
{ System.out.println("Automatic car car* c; method in BMW
features"); } } BMW b; c.show() # Calls the overridden
public class Main c = &b; show method in BMW
{ c->print();
public static void main(String[] args) c->show();
{ return 0;
Car c= new Car(); // Base class }
Subscribe Infeepedia youtube channel for computer science competitive exams
Download Infeepedia app and call or wapp on 8004391758
OOPs Infeepedia By: Infee Tripathi
reference
BMW b = new BMW(); // Derived
class object
c.print(); // Calls the `print`
method of the base class (no
overriding here)

c = b; // Base class reference


pointing to derived class object
c.show(); // Calls the overridden
`show` method in the derived class
(runtime polymorphism)
}}
Output:
This is a basic car
Automatic car features

Difference Between Compile-Time Polymorphism and Run-Time Polymorphism

Aspect Compile-Time Polymorphism Run-Time Polymorphism


Definition The method call is resolved at compile time. The method call is resolved at runtime.
Other Names Static binding, early binding, overloading. Dynamic binding, late binding, overriding.
Inheritance Inheritance is not required. Inheritance is required.
Implementation Achieved through function overloading and Achieved through method overriding and
operator overloading. virtual functions.
Execution Speed Faster, as the method to execute is Slower, as the method to execute is determined
determined during compilation. at runtime.
Flexibility Less flexible because decisions are made at More flexible because decisions are made at
compile time. runtime.
Method Methods with the same name but different Methods with the same name and parameters
Signature parameters or return types. in different classes.
Examples in C++ Function Overloading Virtual Functions
Operator Overloading Pointers to Base Class
Examples in Java Method Overloading Method Overriding
Using @Override Annotation
Examples in Default Arguments Method Overriding
Python Method Overloading (limited support)

Virtual function
 It is supported in C++.
 It is declared using ‘virtual’ keyword.
 It is used to achieve function overriding in run-time polymorphism.
 When a base class pointer object pointing to derived class object but still access base class methods then we use virtual
keyword to resolve this conflict.
 No matter what kind of pointer or reference is used for the function Call virtual functions ensure that the right function is
called for an object.
 Virtual functions cannot be static.
 Virtual functions should have the same prototype in the base class and any derivations.
 A virtual function can be a friend function of another class.
 Virtual functions should be accessed using a pointer or reference of base class type to achieve runtime polymorphism.
 A class may have a virtual destructor but it cannot have a virtual constructor.

Subscribe Infeepedia youtube channel for computer science competitive exams


Download Infeepedia app and call or wapp on 8004391758
OOPs Infeepedia By: Infee Tripathi

Syntax:
class Base {
public:
virtual void show() {
cout << "Base class show()" << endl;
} };
class Derived : public Base {
public:
void show() override { // Override base class method
cout << "Derived class show()" << endl;
} };

Java: Virtual Functions


 In Java, all non-static methods are virtual by default.
 The final keyword can be used to prevent overriding, making a method non-virtual.
 Polymorphism in Java is achieved through method overriding.
 Methods are resolved at runtime based on the actual object type (dynamic method dispatch).
Syntax:
class Base {
public void show() {
System.out.println("Base class show()");
} }
class Derived extends Base {
@Override
public void show() {
System.out.println("Derived class show()");
} }

Python: Virtual Functions


 In Python, all methods are virtual by default.
 Overriding is achieved by defining a method in the derived class with the same name as in the base class.
 Polymorphism is inherent in Python because of its dynamic nature.
 Methods are resolved at runtime based on the actual object type.
Syntax:
class Base:
def show(self):
print("Base class show()")
class Derived(Base):
def show(self):
print("Derived class show()")

Java CPP Python


class Vehicle { #include <iostream> class Vehicle:
public void start() { using namespace std; def start(self):
System.out.println("Vehicle class Vehicle print("Vehicle Started")
started"); { public:
} } virtual void start() class car(Vehicle):
class Car extends Vehicle { { cout << "Vehicle started" << endl; def start(self):
@Override } }; print("Car Started")
public void start() { class Car : public Vehicle
System.out.println("Car { public: void start() override { # Main Program
Subscribe Infeepedia youtube channel for computer science competitive exams
Download Infeepedia app and call or wapp on 8004391758
OOPs Infeepedia By: Infee Tripathi
started"); cout << "Car started" << endl; } }; Vehicle_ref = car() # Base class
} } int main() reference to Derived object
public class Main { { Vehicle* v = new Car(); Vehicle_ref.start() # Output:
public static void main(String[] // Base class pointer to derived class object Derived class show()
args) { v->start();
Vehicle v = new Car(); // Base // Calls Car's start() at runtime
class reference to derived class delete v;
object return 0;
v.start(); // Calls Car's start() at }
runtime
} }
Output:
Car started
Comparison of Virtual Functions in C++, Java and Python

Feature C++ Java Python


Default Behavior Non-virtual by default Virtual by default Virtual by default
Keyword virtual No keyword (all non-static are No keyword required
virtual)
Override Optional (override keyword is Recommended (@Override Implicitly overridden
Enforcement optional) annotation)
Final Methods Use final keyword to prevent Use final keyword No direct equivalent (not override
override by convention)
Polymorphism Requires virtual keyword Achieved via overriding Achieved via overriding
Method Resolution Determined at runtime Determined at runtime Determined at runtime (dynamic
(vtable) (dynamic dispatch) typing)

In C++: Pure Virtual Functions


 A pure virtual function is a function that must be implemented by derived classes, making the base class abstract.
 The implementation is deferred to the derived class, ensuring that the derived classes provide their own specific behavior
for that function.
 A pure virtual function is declared in a base class by assigning = 0 to the function declaration.
 A class containing at least one pure virtual function becomes an abstract class and cannot be instantiated.
 The derived class must implement the pure virtual function; otherwise, it will also become abstract.
 Abstract classes cannot be instantiated directly.
Syntax:
class Base {
public:
virtual void function() = 0; // Pure virtual function
};

Java: Abstract Methods


 In Java, a pure virtual function is called an abstract method.
 Declared using the abstract keyword in an abstract class.
 Abstract methods have no body and must be implemented by derived (sub)classes.
 A class containing at least one abstract method must be declared as abstract.
 Abstract classes cannot be instantiated.
 Subclasses must provide concrete implementations for all abstract methods.

Subscribe Infeepedia youtube channel for computer science competitive exams


Download Infeepedia app and call or wapp on 8004391758
OOPs Infeepedia By: Infee Tripathi

Syntax:
abstract class Base {
abstract void show(); // Abstract method
}

Python: Abstract Methods


 In Python, abstract methods are defined in a base class using the @abstractmethod decorator from the abc (Abstract
Base Class) module.
 A class containing abstract methods becomes an abstract class and cannot be instantiated.
 The ABC module is used to create abstract base classes.
 Abstract methods must be implemented in derived classes.
 Attempting to instantiate an abstract class will result in a TypeError.

Syntax:
from abc import ABC, abstractmethod
class Base(ABC):
@abstractmethod
def show(self):
pass

Java CPP Python


abstract class Shape { #include <iostream> from abc import ABC, abstractmethod
abstract void draw(); // Abstract using namespace std;
method class Shape { class Shape(ABC):
} public: @abstractmethod
class Circle extends Shape { virtual void draw() = 0; // Pure virtual def draw(self):
@Override function pass
void draw() { };
System.out.println("Drawing class Circle : public Shape { class Circle(Shape):
Circle"); public: def draw(self):
} void draw() override { print("Drawing Circle")
} cout << "Drawing Circle" << endl;
public class Main { } # Main Program
public static void main(String[] args) { }; shape = Circle()
Shape shape = new Circle(); int main() { shape.draw() # Output: Drawing Circle
shape.draw(); // Output: Drawing Shape* shape = new Circle();
Circle shape->draw(); // Output: Drawing
} Circle
} delete shape;
return 0;
}

Comparison of Pure Virtual Functions in C++, Java and Python

Feature C++ Java Python


Keyword =0 abstract @abstractmethod
Base Class Abstract if it has pure virtual Abstract if it has abstract Abstract if it has abstract
Inheritance Derived classes must implement Subclasses must implement Subclasses must implement
Instantiation Not allowed for abstract class Not allowed for abstract class Not allowed for abstract class
Modules/Headers No special header needed No special imports Requires abc module

Subscribe Infeepedia youtube channel for computer science competitive exams


Download Infeepedia app and call or wapp on 8004391758
OOPs Infeepedia By: Infee Tripathi

Abstract Class
An abstract class serves as a blueprint for other classes. It cannot be instantiated directly and is used to define common
behaviors that must be implemented by derived or child classes.

In C++: Abstract Class


 An abstract class is a class that contains at least one pure virtual function.
 A pure virtual function is declared by assigning = 0 to the function declaration.
 Abstract classes cannot be instantiated.
 Derived classes must implement all pure virtual functions, or they will also become abstract.
 Abstract classes can have constructors, destructors, and concrete (non-pure virtual) functions.

Syntax:
class AbstractClass {
public:
virtual void abstractMethod() = 0; // Pure virtual function
void concreteMethod() {
cout << "Concrete method in abstract class" << endl;
}
};
In Java: Abstract Class
 An abstract class is declared using the abstract keyword.
 It can contain both abstract methods (without a body) and concrete methods (with a body).
 Abstract classes cannot be instantiated.
 Subclasses must provide implementations for all abstract methods unless the subclass is also abstract.
 Abstract classes can have constructors, which are called when a subclass object is created.

Syntax:
abstract class AbstractClass {
abstract void abstractMethod(); // Abstract method
void concreteMethod() {
System.out.println("Concrete method in abstract class");
}
}

In Python: Abstract Class


 Abstract classes in Python are defined using the ABC (Abstract Base Class) module.
 Methods are marked as abstract using the @abstractmethod decorator.
 Abstract classes cannot be instantiated.
 Subclasses must implement all abstract methods.
 Abstract classes can have concrete methods as well.
Syntax:
from abc import ABC, abstractmethod

class AbstractClass(ABC):
@abstractmethod
def abstract_method(self):
pass
def concrete_method(self):
print("Concrete method in abstract class")

Subscribe Infeepedia youtube channel for computer science competitive exams


Download Infeepedia app and call or wapp on 8004391758
OOPs Infeepedia By: Infee Tripathi
Java CPP Python
abstract class Shape { #include <iostream>
abstract void draw(); // Abstract using namespace std; from abc import ABC, abstractmethod
method
} class Shape { class Shape(ABC):
public: @abstractmethod
class Circle extends Shape { virtual void draw() = 0; // Pure virtual def draw(self):
@Override function pass
void draw() { };
class Circle(Shape):
System.out.println("Drawing Circle"); class Circle : public Shape { def draw(self):
} public: print("Drawing Circle")
} void draw() override {
public class Main { cout << "Drawing Circle" << endl; # Main Program
public static void main(String[] args) { } shape = Circle()
Shape shape = new Circle(); }; shape.draw() # Output: Drawing Circle
shape.draw(); // Output: Drawing int main() {
Circle Shape* shape = new Circle();
} shape->draw(); // Output: Drawing
} Circle
delete shape;
return 0;
}

Comparison of Abstract Classes


Feature C++ Java Python
Definition Contains at least one pure virtual Declared with abstract Uses ABC and @abstractmethod
function keyword
Instantiation Not allowed Not allowed Not allowed
Concrete Methods Allowed Allowed Allowed
Abstract Methods Declared with = 0 Declared with abstract Declared with @abstractmethod
keyword
Inheritance Derived classes must implement Subclasses must implement Subclasses must implement
pure virtual functions abstract methods abstract methods
Modules/Headers No special header needed No special imports Requires abc module

Interfaces
An interface is a programming construct that defines a contract or a set of methods that a class must implement.
Interfaces are commonly used to achieve abstraction and multiple inheritance in java.

C++: Interfaces (pure abstract class)


 C++ does not have a built-in interface keyword, but interfaces can be implemented using abstract classes with only pure
virtual functions.
 An interface in C++ is typically an abstract class with all methods declared as pure virtual (= 0).
 Classes implementing the interface must define all pure virtual functions.
 Multiple inheritance can be used to implement multiple interfaces.
 Interfaces cannot have any implementation (only declarations).

Subscribe Infeepedia youtube channel for computer science competitive exams


Download Infeepedia app and call or wapp on 8004391758
OOPs Infeepedia By: Infee Tripathi
Syntax:
class Interface {
public:
virtual void method1() = 0; // Pure virtual function
virtual void method2() = 0;
virtual ~Interface() {} // Virtual destructor
};

Java CPP Python


class Implementation implements #include <iostream> from abc import ABC, abstractmethod
Interface { using namespace std;
@Override class Interface { class Interface(ABC):
public void method1() { public: @abstractmethod
System.out.println("Method1 virtual void method1() = 0; def method1(self):
implemented"); virtual void method2() = 0; pass
} virtual ~Interface() {}
}; @abstractmethod
@Override class Implementation : public Interface def method2(self):
public void method2() { { pass
System.out.println("Method2 public:
implemented"); void method1() override { class Implementation(Interface):
} cout << "Method1 implemented" def method1(self):
} << endl; print("Method1 implemented")
public class Main { }
public static void main(String[] args) { void method2() override { def method2(self):
Interface obj = new cout << "Method2 implemented" print("Method2 implemented")
Implementation(); << endl;
obj.method1(); // Output: Method1 } # Main Program
implemented }; obj = Implementation()
obj.method2(); // Output: Method2 int main() { obj.method1() # Output: Method1
implemented Interface* obj = new implemented
} Implementation(); obj.method2() # Output: Method2
} obj->method1(); // Output: implemented
Method1 implemented
obj->method2(); // Output:
Method2 implemented
delete obj;
return 0;
}

Java: Interfaces
 Java provides a built-in interface keyword to define interfaces.
 An interface in Java is a reference type that contains abstract methods (by default) and constants.
 Starting from Java 8, interfaces can also have default methods and static methods.
 Methods in interfaces are public and abstract by default.
 Fields in interfaces are public, static, and final by default.
 A class can implement multiple interfaces.
Syntax:
interface Interface {
void method1(); // Abstract method
void method2();
}
Subscribe Infeepedia youtube channel for computer science competitive exams
Download Infeepedia app and call or wapp on 8004391758
OOPs Infeepedia By: Infee Tripathi
interface Interface {
void method1();
void method2();
}

Python: Interfaces (abstract base class)


 Python does not have a built-in interface keyword, but interfaces can be implemented using the abc module (Abstract
Base Classes).
 An interface in Python is defined as an abstract base class (ABC) with abstract methods.
 Abstract methods are declared using the @abstractmethod decorator.
 Classes implementing the interface must define all abstract methods.
 Python supports multiple inheritance, allowing classes to implement multiple interfaces.
Syntax:
from abc import ABC, abstractmethod
class Interface(ABC):
@abstractmethod
def method1(self):
pass
@abstractmethod
def method2(self):
pass

Comparison of Interfaces
Feature C++ Java Python
Definition Abstract class with pure virtual methods interface keyword Abstract Base Class (ABC)
Keyword No specific keyword interface @abstractmethod decorator
Multiple Interfaces Supported via multiple inheritance Supported Supported
Default Methods Not allowed Allowed (from Java 8) Not directly supported
Static Methods Not allowed Allowed (from Java 8) Allowed in Python classes
Fields No restrictions public static final by default No special restrictions

Abstraction
 Abstraction is a fundamental concept in object-oriented programming (OOP) that hides implementation details and
exposes only essential features of an object.
 It focuses on what an object does rather than how it does it.

C++: Abstraction
 Achieved using abstract classes and pure virtual functions.
 Hides the implementation details of methods and enforces derived classes to provide their own implementations.
 A class with at least one pure virtual function (= 0) is abstract.
 Abstract classes cannot be instantiated.
 Abstraction can also be achieved using encapsulation by making members private or protected.
Syntax:
class AbstractClass {
public:
virtual void abstractMethod() = 0; // Pure virtual function
void concreteMethod() {
cout << "Concrete method in abstract class" << endl;
}
};

Subscribe Infeepedia youtube channel for computer science competitive exams


Download Infeepedia app and call or wapp on 8004391758
OOPs Infeepedia By: Infee Tripathi
Java: Abstraction
 Achieved using abstract classes and interfaces.
 Abstract classes can have both abstract methods (without a body) and concrete methods (with a body).
 Interfaces define a contract that implementing classes must follow.
 Abstract classes are declared using the abstract keyword.
 Interfaces are declared using the interface keyword.
 Abstract classes and interfaces cannot be instantiated.
Syntax:
abstract class AbstractClass {
abstract void abstractMethod(); // Abstract method
void concreteMethod() {
System.out.println("Concrete method in abstract class");
}
}

Python: Abstraction
 Achieved using the abc module (Abstract Base Class).
 Abstract methods are declared using the @abstractmethod decorator.
 Abstract classes cannot be instantiated.
 Subclasses must implement all abstract methods.
 Python does not have an abstract keyword; abstraction is implemented through abc.

Syntax:
from abc import ABC, abstractmethod
class AbstractClass(ABC):
@abstractmethod
def abstract_method(self):
pass
def concrete_method(self):
print("Concrete method in abstract class")

Java CPP Python


abstract class Shape { #include <iostream> from abc import ABC, abstractmethod
abstract void draw(); // Abstract using namespace std;
method class Shape { class Shape(ABC):
} public: @abstractmethod
virtual void draw() = 0; // Pure def draw(self):
class Circle extends Shape { virtual function pass
@Override };
void draw() { class Circle : public Shape { class Circle(Shape):
System.out.println("Drawing public: def draw(self):
Circle"); void draw() override { print("Drawing Circle")
} cout << "Drawing Circle" << endl;
} } # Main Program
}; shape = Circle()
public class Main { int main() { shape.draw() # Output: Drawing
public static void main(String[] args) { Shape* shape = new Circle(); Circle
Shape shape = new Circle(); shape->draw(); // Output: Drawing
shape.draw(); // Output: Drawing Circle
Circle delete shape;
} return 0;
} }
Subscribe Infeepedia youtube channel for computer science competitive exams
Download Infeepedia app and call or wapp on 8004391758
OOPs Infeepedia By: Infee Tripathi
Comparison of Abstraction
Feature C++ Java Python
Definition Achieved using abstract classes Achieved using abstract classes Achieved using abc module
and interfaces
Instantiation Abstract classes cannot be Abstract classes and interfaces Abstract classes cannot be
instantiated cannot be instantiated instantiated
Abstract Methods Declared using = 0 Declared with abstract keyword Declared with @abstractmethod
Concrete Methods Allowed in abstract classes Allowed in abstract classes Allowed in abstract classes
Interfaces No dedicated interface keyword; Use interface keyword No dedicated interface keyword;
use abstract classes use abc
Multiple Supported Supported via interfaces Supported
Inheritance

C++: this Keyword


 this is a pointer that refers to the current instance of the class.
 It is implicitly passed to all non-static member functions of a class.
 this is not available in static member functions because they are not tied to any specific object.
 Accessing members of the current object.
 Resolving naming conflicts between instance variables and method parameters.
 Returning the current object (e.g., for method chaining).

Java: this Keyword


 this is a reference to the current instance of the class.
 It is implicitly available in all non-static methods and constructors.
 this is not accessible in static methods.
 Referring to instance variables when they are shadowed by method or constructor parameters.
 Invoking other constructors in the same class using this() (constructor chaining).
 Passing the current object as an argument to a method or constructor.

Python: self Keyword


 Python uses self instead of this.
 It refers to the current instance of the class and is explicitly passed as the first parameter to instance methods.
 In Python, self is not a keyword but a convention.
 Accessing instance variables and methods of the current object.
 Resolving naming conflicts between instance variables and method parameters.
Java CPP Python
class Person { #include <iostream> class Person:
private String name; using namespace std; def __init__(self, name):
// Constructor self.name = name # Resolves
Person(String name) { class Person { naming conflict
this.name = name; // Resolves private:
naming conflict string name; def display(self):
} public: print(f"Name: {self.name}") #
void display() { Person(string name) { Accessing the current object's member
System.out.println("Name: " + this->name = name; // Resolves
this.name); // Accessing the current naming conflict def get_self(self):
object's member } return self # Returning the current
} void display() { object
Person getThis() { cout << "Name: " << this->name << endl;
Subscribe Infeepedia youtube channel for computer science competitive exams
Download Infeepedia app and call or wapp on 8004391758
OOPs Infeepedia By: Infee Tripathi
return this; // Returning the current // Accessing the current object's # Main Program
object member p = Person("Alice")
} } p.display() # Output: Name: Alice
} print(f"Address of object:
public class Main { Person* getThis() { {p.get_self()}")
public static void main(String[] args) { return this; // Returning the current
Person p = new Person("Alice"); object
p.display(); // Output: Name: Alice }
System.out.println("Address of };
object: " + p.getThis());
} int main() {
} Person p("Alice");
p.display(); // Output: Name: Alice
cout << "Address of object: " <<
p.getThis() << endl;
return 0;
}

Comparison of this/self in C++, Java, and Python

Feature C++ this Java this Python self


Definition Pointer to the current object Reference to the current object Reference to the current object
Implicit/Explicit Implicit in all non-static Implicit in all non-static methods Explicit in method definitions
methods
Static Method Not available Not available Not applicable (explicit in
Access Python)
Constructor Not used for constructor Used for constructor chaining (this()) Not used for constructor chaining
Usage chaining
Naming Keyword Keyword Convention (not a keyword)
Key Purpose Access members and resolve Access members, resolve conflicts, Access members, resolve
conflicts constructor chaining conflicts

super Keyword
The super keyword (in java) is used to refer to the parent class of the current class. It allows access to the parent class's
methods, constructors, or attributes that are overridden or shadowed in the child class.

C++: Base Class Access


 C++ does not have a super keyword.
 Instead, the name of the parent (base) class is used explicitly to access overridden methods or constructors.
 Call the base class's constructor from the derived class.
 Access base class members or methods that are overridden in the derived class.

Java: super Keyword


 super is a keyword in Java used to refer to the immediate parent class.
 It is used in constructors and methods to access the parent class's methods, attributes, or constructors.
 Call the parent class's constructor using super().
 Access parent class methods or attributes that are overridden or shadowed in the child class.

Subscribe Infeepedia youtube channel for computer science competitive exams


Download Infeepedia app and call or wapp on 8004391758
OOPs Infeepedia By: Infee Tripathi
Python: super Keyword
 super() is a built-in function in Python used to refer to the parent class.
 It is commonly used in class inheritance to access parent class methods, attributes, or constructors.
 Call the parent class's __init__ method in the child class constructor.
 Access parent class methods that are overridden in the child class.

Comparison of super Keyword


Feature C++ (Base Class Access) Java super Python super()
Keyword No super keyword, use base class name super keyword super() function
Constructor Call Explicitly call base class constructor Use super() in the constructor Use super().__init__()
Method Access Use base class name explicitly Use super.methodName() Use super().methodName()
Attribute Access Use base class name explicitly Use super.attributeName Use super().attributeName
Dynamic No Yes Yes
Dispatch

Final keyword
The final keyword (or its equivalent in Python) is used to prevent further modifications in terms of inheritance or
overriding. Its usage and behavior vary across C++, Java, and Python.

C++: final
 Introduced in C++11, the final keyword prevents a class from being inherited or a virtual method from being overridden in
derived classes.
 Mark a class as final to prevent inheritance.
 Mark a virtual function as final to prevent overriding in derived classes.

Java: final
 The final keyword in Java can be applied to variables, methods, and classes.
 It prevents variables from being reassigned, methods from being overridden, and classes from being inherited.
 Mark a class as final to prevent inheritance.
 Mark a method as final to prevent overriding.
 Mark a variable as final to make it a constant (its value cannot be changed after initialization).

Python: final (via @final Decorator)


 Python does not have a final keyword but provides the @final decorator in the typing module (introduced in Python 3.8).
 The @final decorator is used to mark methods or classes as final, signaling that they should not be overridden or
inherited.
 Mark a method as @final to prevent overriding.
 Mark a class as @final to prevent inheritance.

Comparison of final in C++, Java, and Python

Feature C++ final Java final Python @final


Prevent Class Inheritance final before class final before class name @final decorator on class
name
Prevent Method Overriding final after method final before method name @final decorator on method
name
Prevent Variable Not applicable final before variable Not natively supported (use
Reassignment constants)
Availability Since C++11 Always Since Python 3.8

Subscribe Infeepedia youtube channel for computer science competitive exams


Download Infeepedia app and call or wapp on 8004391758
OOPs Infeepedia By: Infee Tripathi
Inline Functions
C++: Inline Functions
 In C++, an inline function is a request to the compiler to replace the function call with the function's body to reduce
function call overhead.
 It is defined using the inline keyword.
 Used for small functions to improve performance.
 The compiler may ignore the inline request if the function is too complex.
 Defined either inside the class or using the inline keyword.

 Inline functions reduce function call overhead and improve program performance.
 They are suitable for small programs and are declared using the inline keyword.
 Inline functions save stack overhead during function calls.
 All functions defined inside a class are implicitly inline.
 Inline functions cannot be used with loops, static variables, switch, goto, or recursion.
 Virtual functions cannot be inline because they are resolved at runtime.
 Inline functions enable the compiler to perform context-specific optimizations.
 Excessive use of inline functions increases binary size and reduces instruction cache efficiency.
 Modifying inline function code can increase compile-time overhead.
 Inline functions are preferred over macros due to type safety and compiler management.
 Unlike macros, inline functions can access private members of a class.

Java: Inline Functions (Implicit with JVM)


 Java does not have an explicit inline keyword.
 The Just-In-Time (JIT) compiler in the JVM automatically performs method inlining for small, frequently called methods.
 The decision to inline is handled by the JVM during runtime.
 Methods defined inside an interface or as final or static are more likely to be inlined because they cannot be overridden.

Python: Inline Functions (Simulated with Lambda or JIT)


 Python does not have a native inline keyword.
 Functions can be inlined manually using lambda expressions for simple cases.
 Advanced optimizations like inlining can be achieved using libraries like Numba or PyPy.
 Lambdas provide a concise way to define small functions inline.
 For performance improvement, JIT compilers like Numba can be used.

class Main { #include <iostream> add = lambda a, b: a + b # Inline


static int add(int a, int b) { // JVM using namespace std; function using lambda
may inline this method inline int add(int a, int b) { return a + result = add(5, 10)
return a + b; } b; } print("Result:", result)
public static void main(String[] args) { int main() { def add(a, b):
int result = add(5, 10); // JVM int result = add(5, 10); // Function return a + b
decides if inlining is beneficial body is inserted here result = add(5, 10) # Function call (no
System.out.println("Result: " + cout << "Result: " << result << endl; true inlining in Python)
result); } } return 0; print("Result:", result)
} Using Numba for JIT Optimization:
from numba import jit
@jit(nopython=True)
def add(a, b):
return a + b
result = add(5, 10) # JIT compiler
optimizes the function
print("Result:", result)
Subscribe Infeepedia youtube channel for computer science competitive exams
Download Infeepedia app and call or wapp on 8004391758
OOPs Infeepedia By: Infee Tripathi
Comparison of Inline Functions
Feature C++ Java Python
Keyword inline No explicit keyword No explicit keyword
Inlining Control Programmer-defined (inline) Handled by JVM (JIT) Simulated with lambdas or JIT
Compiler Behavior Compiler decides to inline JVM decides to inline No native compiler support
Use for Small Functions Yes Yes Yes (via lambdas or JIT)
Support for Recursion Not suitable JVM avoids inlining recursion No native support

Static Keyword Variable, Function, and Class in C++, Java, and Python
The concept of static is used to define variables, functions, or classes that are associated with a class rather than an
instance. Its behavior varies across C++, Java, and Python.

In C++: Static variable and functions


Static variable
 Static variables are declared using the static keyword and are initialized to zero by default.
 They can be declared inside functions or classes.
 When declared in a function, static variables retain their value throughout the lifetime of the program.
 In a class, only one copy of a static variable is created, and it is shared by all objects of the class.
 Static variables are visible only within their defined scope.
 They are initialized before any class object is created, even before the main() function starts.
 Static variables cannot be initialized using constructors.
 A static variable in a class must be explicitly initialized outside the class using the class name and the scope resolution
operator (::).
 Static objects also exist for the entire lifetime of the program.

Static Member Functions:


 Static member functions can only access static variables or other static functions within the class.
 They cannot access non-static variables or member functions.
 Static functions are only accessible within the class in which they are defined.

Uses of Static:
 To define variables with static storage duration and internal linkage.
 To declare block-scope variables that are initialized only once.
 To define class members that are shared across all instances of the class.

#include <iostream> #include <iostream>


using namespace std; using namespace std;
class Test { class Test {
public: public:
static int count; // Static variable declaration static void display() { // Static function
Test() { count++; } // Increment static variable cout << "Static function called" << endl;
}; }
int Test::count = 0; // Static variable definition };
int main() { int main() {
Test t1, t2, t3; Test::display(); // Call using class name
cout << "Count: " << Test::count << endl; // Access return 0;
using class name }
return 0;
}

Subscribe Infeepedia youtube channel for computer science competitive exams


Download Infeepedia app and call or wapp on 8004391758
OOPs Infeepedia By: Infee Tripathi
In Java: Static Keyword
Static Variable
 It is declared using the static keyword.
 Shared among all objects of the class (only one copy exists for the class).
 Initialized only once when the class is loaded into memory.
 Commonly used for constants or shared data.

Static Method
 A static method belongs to the class and cannot access non-static members directly.
 It is invoked using the class name.
 It can be called without creating an object of the class.
 Commonly used for utility or helper methods.

Static Class
 Java does not allow top-level classes to be static, but nested classes can be declared static.
 Useful for grouping utility methods.

Static Blocks
 Used to initialize static variables.
 Executes only once when the class is loaded into memory.
 Runs before the main() method or any static methods.
class Example
{ static int value;
static
{ value = 100; // Static block
System.out.println("Static block executed"); } }

Static variable Static function Static Class


class Test { class Test { class Outer {
static int count = 0; // Static static void display() { // Static method static class Inner { // Static nested class
variable System.out.println("Static method void display() {
Test() { called"); System.out.println("Static nested
count++; } class method");
} } }
} public class Main { }
public class Main { public static void main(String[] args) { }
public static void main(String[] Test.display(); // Call using class public class Main {
args) { name public static void main(String[] args) {
new Test(); } Outer.Inner obj = new Outer.Inner();
new Test(); } // Create instance of static nested class
System.out.println("Count: " + obj.display();
Test.count); // Access using class }
name }
}
}

Subscribe Infeepedia youtube channel for computer science competitive exams


Download Infeepedia app and call or wapp on 8004391758
OOPs Infeepedia By: Infee Tripathi
In Python: Static Keyword
Python does not have a static keyword like Java or C++, but it provides similar functionality using class variables,
staticmethods, and class methods.

Static Variables (Class Variables)


 Variables defined at the class level, shared across all instances of the class.
 Changes to a static variable affect all instances of the class.
Static Method
 Defined using the @staticmethod decorator.
 Do not require access to instance or class-specific data.
 Can be called using the class name or an instance.
Static Class
 Python does not have a static class keyword, but a class can contain only static methods and variables, making it
effectively static.
 Used for utility functions or constants.

class Test: class Test: class StaticClass:


count = 0 # Static variable @staticmethod @staticmethod
def __init__(self): def display(): # Static method def utility_function():
Test.count += 1 # Access using class print("Static method called") print("Utility function in static
name class")
Test.display() # Call using class name
t1 = Test() StaticClass.utility_function()
t2 = Test()
print("Count:", Test.count) # Access
using class name

Feature C++ Java Python


Static Shared among instances, Shared among instances, Shared among instances, defined at
Variable defined with static. defined with static. class level.
Static Defined with static, cannot Defined with static, cannot Defined with @staticmethod, cannot
Function access non-static members. access non-static members. access instance variables.
Static Class No keyword, can create classes Top-level classes cannot be No keyword, can simulate with static
with only static members. static, but nested classes can. methods and variables.

Constants in C++
Constant Variable
A variable declared with the const keyword. Its value must be initialized at the time of declaration and cannot be modified
after initialization.
The const keyword can be used with pointers to make the value or the pointer itself constant.
Syntax:
const <data_type> <variable_name> = <value>;

const int x = 10; // Constant variable x const int* ptr = &x; // Data is
= 20; // Error: Cannot modify a const constant, pointer can change
variable *ptr = 20; // Error: Cannot modify the
data
ptr = &y; // Valid: Pointer can point to
another variable

Subscribe Infeepedia youtube channel for computer science competitive exams


Download Infeepedia app and call or wapp on 8004391758
OOPs Infeepedia By: Infee Tripathi
Constant Pointers
The const keyword can be used with pointers to make the value or the pointer itself constant.

Pointer to Constant Data Constant Pointer to Data Constant Pointer to Constant Data
const int* ptr = &x; // Data is constant, int* const ptr = &x; // Pointer is const int* const ptr = &x; // Both
pointer can change constant, data can change pointer and data are constant
*ptr = 20; // Error: Cannot modify ptr = &y; // Error: Cannot change *ptr = 20; // Error: Cannot
the data the pointer modify the data
ptr = &y; // Valid: Pointer can *ptr = 20; // Valid: Data can be ptr = &y; // Error: Cannot
point to another variable modified change the pointer

Constant Function
 Declared with const after the function name.
 Ensures the function does not modify any member variables of the class.
 Syntax:
<return_type> <function_name>() const;

Constant Function Parameters: Prevents modification of arguments passed to a function.


Constant Return Values: Ensures the returned value cannot be modified by the caller.
Constant Objects: Objects declared as const can only call const member functions.

Constant Function Constant Function Parameters Constant Return Values Constant Objects
class Example void display(const int value) { const int getValue() { const Example obj;
{ int x; // value = 20; // Error: return 10; // obj.modify(); // Error:
public: void display() const Cannot modify a const } Cannot call non-const
{ parameter int x = getValue(); function
x = 20; // Error: Cannot std::cout << value << x = 20; // Valid: x is not const obj.display(); // Valid: Can
modify member variables std::endl; call const function
std::cout << x << std::endl; }
} };

Final (Constants) in Java


 Java does not have a direct const keyword; the final keyword is used to create constants in Java.
 A final variable must be initialized once and cannot be changed.
 static final is used for global constants shared across all instances.
 final methods cannot be overridden, and final classes cannot be extended.

Constant Variables Static Final Constants Final Parameters Final Methods


class Example { class Example { class Example { class Parent {
final int CONSTANT_VALUE static final double PI = void display(final int value) final void display() {
= 100; // Constant variable 3.14159; // Static constant { System.out.println("This is
void display() void display() { // value = 20; // Error: a final method");
// CONSTANT_VALUE = 200; System.out.println("Value of Cannot modify final } }
// Error: Cannot reassign a PI: " + PI); parameter class Child extends Parent {
final variable } System.out.println(value); // void display() { }
System.out.println(CONSTANT } } // Error: Cannot override a
_VALUE); } } } final method }

Subscribe Infeepedia youtube channel for computer science competitive exams


Download Infeepedia app and call or wapp on 8004391758
OOPs Infeepedia By: Infee Tripathi
Final Classes: Prevents a class from being inherited.
Example:
final class Example {
void display() {
System.out.println("This is a final class");
}
}
// class SubExample extends Example { } // Error: Cannot inherit from a final class

Constants in Python
 Python does not have a built-in const or final keyword.
 By convention, constants are written in uppercase (e.g., PI, GRAVITY).
 Constants can be stored in separate modules for better organization.
 The Final annotation from typing (introduced in Python 3.8) provides an optional way to indicate constants but does not
enforce immutability.
 Python constants rely on developer discipline rather than enforced immutability.

Constants variable Constant Function Constant Class


PI = 3.14 # Constant variable by def display(): # Function treated as constant from dataclasses import dataclass
convention print("This is a constant function.")
print("Value of PI:", PI) display() @dataclass(frozen=True)
# PI = 3.14159 # Allowed but class Test:
discouraged value: int

t = Test(10)
print("Value:", t.value)
# t.value = 20 # Error: Cannot assign to
field

Comparision of constant in C++, Java and Python

Feature C++ Java Python


Constant const keyword, value final keyword, value immutable. Naming convention (all-uppercase).
Variable immutable.
Constant Declared with const, cannot No direct equivalent; use final to Functions that avoid state
Function modify state. prevent overriding. modification.
Constant Class No direct keyword, but Declared with final, cannot be Use @dataclass(frozen=True) for
members can be const. subclassed. immutability.

Friend Function and Class in C++


Friend Class
 Declared using the friend keyword.
 Allows one class to access the private and protected members of another class.
 Can be declared in any access block (private, protected, or public).
 The friend keyword is used only in the declaration, not in the function definition or calls.
Example:
#include <iostream>
using namespace std;
class Car {
private:
int x;
public:
Subscribe Infeepedia youtube channel for computer science competitive exams
Download Infeepedia app and call or wapp on 8004391758
OOPs Infeepedia By: Infee Tripathi
Car() { x = 45; }
friend class Auto; // Declaring Auto as a friend class
};
class Auto {
public:
void show(Car &obj) {
cout << "Private Variable of Car class = " << obj.x << endl;
}
};
int main() {
Car c;
Auto a;
a.show(c);
return 0;
}
// Output: Private Variable of Car class = 45

Friend Function
 A non-member function declared as a friend can access private and protected members of a class.
 The friend keyword is used only in the declaration, not in the definition or when calling the function.
 Friend functions are called like normal functions, not with an object and dot operator.
 It can be:
1. A global function.
2. A member function of another class.
Syntax:
friend return_type function_name(arguments); // Global function

friend return_type class_name::function_name(arguments); // Member function of another class

Friend Function and Class in Java


 Java doesn't have a friend keyword as in C++.
 Use package-private (default access) for friend-like functionality within the same package.
 Use protected for access in subclasses across packages.
 Java promotes encapsulation and controlled access using getter and setter methods, instead of directly exposing private
members.
 By using these mechanisms, Java achieves similar functionality to friend functions and classes in a more controlled and
secure manner.

Friend Function and Class in Python


Python does not have a friend keyword. However, similar functionality can be achieved through:
Access modifiers: Use naming conventions like _ (protected) or __ (private) for attributes.
Direct access: Python allows direct access to private attributes, as it does not enforce strict access restrictions.
In Python, friend-like functionality is achieved through dynamic access, naming conventions, and encapsulation.
Comparison of friend keyword in C++, Java and python
Feature C++ Java Python
Friend friend keyword gives access to Use public getters or package- Access private attributes directly or
Function private data. private access. via methods.
Friend Class friend keyword allows class- Use package-private or protected Access private attributes directly or
level access. access. via methods.

Subscribe Infeepedia youtube channel for computer science competitive exams


Download Infeepedia app and call or wapp on 8004391758

You might also like