Unit 4 ObjectsAD
Unit 4 ObjectsAD
In object-oriented programming (OOP), objects are the basic entities that actually exists
in the memory. Each object is based on a blueprint of attributes and behaviours
(variables and functions) defined as Class.
The basic purpose of a Class is to identify the common attributes and behaviours and
group them as an entity that can be reused again and again for similar purposes. The
Objects are such entities that are created based on these classes to follow that
purpose. All data members and member functions of the class can be accessed with the
help of objects. When a class is defined, no memory is allocated, but memory is
allocated when it is instantiated (i.e. an object is created).
Example of Object
For Example, the objects for the class Account are SBI Account, ICICI account, etc.
Characteristics of an object
As discussed above, every object has some attributes and behaviours, but it is very
important to understand what are the characteristics, that every object must have:
1. Identity: Every object must have a different identity from the other, known as the
object’s name. No two object must have the same name.
2. State: If there are some properties of a class, that is designed to be derived in an
object, it must have some values to get initiated (usually done with the help of
constructors).
3. Behaviour: Now since the object have a name and some properties, it must have
some purpose as well. So these purposes are defined with help of functions
(processes) and are known as behaviours.
Some of the things in programming that can be defined as objects include the following:
Objects can do things and can have things done to them. For example, a function or
method object can be programmed to modify the contents of a data structure or variable
object.
Object-based languages
Object-based languages support the full complement of features of object-oriented
programming. These features are as follows:
• Abstraction means that hiding implementation code that is not necessary for use by
other objects. This helps make it easier for developers to change or add to objects
over time.
• Polymorphism means that an object can mean or be used differently in different
contexts.
• Inheritance means that object classes can reuse code from other classes. For
example, relationships between objects can be assigned to create a class hierarchy,
which enables developers to reuse coding logic to create families of related objects.
• Data encapsulation means that objects contain everything they need to function,
including the object methods and any related data. The object can then make its
interfaces available to other objects to enable them to use the object.
• Java
• Python
• C++
• C#
• Ruby
• PHP
• Lisp
• MATLAB
• R
• NET
• JavaScript
Benefits of using objects in programming
Using objects in programming has become commonplace, as most modern
programming languages now support some or all of the principles of object-oriented
programming. Some of the most important benefits of using objects in programming
include the following:
That is not to say that programming with objects does not have a downside. Some of
the disadvantages of using objects in programming include the following:
• OOP concepts can be difficult to learn and learning to program with objects can be
more complicated than learning to program with procedure programming languages.
• OOP programs can be significantly larger than procedural programs.
• OOP programs can run more slowly than programs written in procedural
programming languages.
The differences between types of programming languages may not be as critical for
simple programs, but for more complex programming projects there are differences that
make one programming framework better than another.
Types of objects
Objects can be categorized based on what they do or how they work. Some of the most
commonly used types of objects include the following:
• Function objects contain a single function and are used similarly to operating
system or programming language functions.
• Immutable objects are not changed after their creation. Data and state of the object
are fixed and are not changed by use of functions.
• Container objects may contain other objects.
• Factory objects are designed to create other objects.
These and other types of objects are based on design patterns, which represent
repeatable solutions to common tasks or problems in programming. The patterns
themselves are not objects but are used to develop objects that fulfill the functions of
those patterns.
God objects are objects that break the rules by doing more than one thing. If you're still
learning object- oriented programming, find out how to refactor the God object class
antipattern. Otherwise, get started with this breakdown of object-oriented programming
concepts.
Messages classes: A Message Class is a programming concept used in object-
oriented languages, which represents a set of messages that objects can send, receive,
and process. It forms the basis for communication between objects in a system, making
it essential for designing software applications.
Definition
Key Takeaways
4. Message Class is a term used in Object-Oriented Programming (OOP) to define
a class or template that represents a message or communication exchanged
between objects in a system.
5. Message Classes encapsulate the data and behavior of messages, allowing for
structured and organized passing of information through various components of a
software application.
6. Implementing Message Classes can enhance code maintainability and increase
the overall effectiveness of communication between objects, making it easier to
manage complex systems and troubleshoot issues.
Importance
Additionally, message classes enable error detection and handling, ensuring the
intended information is exchanged correctly across diverse platforms.
Email Systems: Message classes are used in email systems like Outlook to categorize
different types of email messages. For example, standard email messages have the
IPM.Note message class, while meeting requests have the
IPM.Schedule.Meeting.Request message class. This enables the email client to handle
and display different message types correctly.
While a Message Class focuses on the set of messages that objects can send, receive,
and process, a class in OOP is an abstraction that defines a blueprint for creating
objects. A class typically consists of attributes (data) and methods (actions), while a
Message Class solely focuses on the actions, specifically the communication, that
objects can perform.
To use a Message Class in your software project, you should follow these steps:
In this type of inheritance, a derived class is created from a single base class.
In the given figure, Class A is the parent class and Class B is the child class since Class
B inherits the features and behavior of the parent class A.
2. Multi-level inheritance
In the given figure, class C inherits the properties and behavior of class B and class B
inherits from class A. So, here A is the parent class of B and class B is the parent class
of C. So, here class C implicitly inherits the properties and behavior of Class A along with
Class B i.e. there is a multilevel inheritance.
3. Multiple inheritance
In this inheritance, a derived class is created from more than one base class. This
inheritance is not supported by .NET Languages like C#, F#, etc., and Java Language.
In the given figure, class C inherits the properties and behavior of classes B and A at the
same level. So, here A and B both are the parent classes for Class C.
//Base Class
class A
{
public void fooA()
{
//TO DO:
}
}
//Base Class
class B
{
public void fooB()
{
//TO DO:
}
}
//Derived Class
class C : A, B
{
public void fooC()
{
//TO DO:
}
}
4. Multipath Inheritance
In this inheritance, a derived class is created from other derived classes and the same
base class of other derived classes. This inheritance is not supported by .NET Languages
like C#, F#, etc.
In the given figure, class D inherits the properties and behavior of classes C and B. Both
class C and class B inherit Class A. So, Class A is the parent for Class B and Class C as
well as Class D. So it's making a Multipath inheritance.
//Base Class
class A
{
public void fooA()
{
//TO DO:
}
}
//Derived Class
class B: A
{
public void fooB()
{
//TO DO:
}
}
//Derived Class
class C: A
{
public void fooC()
{
//TO DO:
}
}
//Derived Class
class D: B, C
{
public void fooD()
{
//TO DO:
}
}
5. Hierarchical Inheritance
In this inheritance, more than one derived class is created from a single base class and
further child classes act as parent classes for more than one child class.
In the given figure, class C has two children class A and class B.
Syntax for Hierarchical Inheritance
//Base Class
class C
{
public void fooA()
{
//TO DO:
}
}
//Derived Class
class A: C
{
public void fooB()
{
//TO DO:
}
}
//Derived Class
class B: C
{
public void fooC()
{
//TO DO:
}
}
6. Hybrid Inheritance
//Base Class
class A
{
public void fooA()
{
//TO DO:
}
}
//Derived Class
class C: A
{
public void fooC()
{
//TO DO:
}
}
//Base Class
class F
{
public void fooF()
{
//TO DO:
}
}
//Derived Class
class B: C, F
{
public void fooB()
{
//TO DO:
}
}
Advantages of Inheritance
Disadvantages of Inheritance
26. In inheritance, both base and child classes are tightly coupled. Hence If you
change the code of the parent class, it will affect all the child classes.
27. In a class hierarchy, many data members remain unused and the memory
allocated is not utilized. Hence it affects the performance of your program if you
have not implemented inheritance correctly.
28. Inheritance increases the coupling between the base class and the derived class.
Any small change in the base class will directly affect all child classes that are
extending the parent class.
Polymorphism in OOPs
The word “polymorphism” means having many forms. In simple words, we can define
polymorphism as the ability of a message to be displayed in more than one form. A real-
life example of polymorphism is a person who at the same time can have different
characteristics. A man at the same time is a father, a husband, and an employee. So
the same person exhibits different behavior in different situations. This is called
polymorphism. Polymorphism is considered one of the important features of Object-
Oriented Programming.
Types of Polymorphism
• Compile-time Polymorphism
• Runtime Polymorphism
1. Compile-Time Polymorphism
This type of polymorphism is achieved by function overloading or operator overloading.
A. Function Overloading
When there are multiple functions with the same name but different parameters, then
the functions are said to be overloaded, hence this is known as Function Overloading.
Functions can be overloaded by changing the number of arguments or/and
changing the type of arguments. In simple terms, it is a feature of object-oriented
programming providing many functions that have the same name but distinct
parameters when numerous tasks are listed under one function name. There are certain
Rules of Function Overloading that should be followed while overloading a function.
• C++
// Driver code
int main()
{
Geeks obj1;
Explanation: In the above example, a single function named function func() acts
differently in three different situations, which is a property of polymorphism. To know
more about this, you can refer to the article – Function Overloading in C++.
B. Operator Overloading
C++ has the ability to provide the operators with a special meaning for a data type, this
ability is known as operator overloading. For example, we can make use of the addition
operator (+) for string class to concatenate two strings. We know that the task of this
operator is to add two operands. So a single operator ‘+’, when placed between integer
operands, adds them and when placed between string operands, concatenates them.
• CPP
class Complex {
private:
int real, imag;
public:
Complex(int r = 0, int i = 0)
{
real = r;
imag = i;
}
// Driver code
int main()
{
Complex c1(10, 5), c2(2, 4);
Output12 + i9
Explanation: In the above example, the operator ‘+’ is overloaded. Usually, this
operator is used to add two numbers (integers or floating point numbers), but here the
operator is made to perform the addition of two imaginary or complex numbers. To
know more about this one, refer to the article – Operator Overloading.
2. Runtime Polymorphism
This type of polymorphism is achieved by Function Overriding. Late binding and
dynamic polymorphism are other names for runtime polymorphism. The function call is
resolved at runtime in runtime polymorphism. In contrast, with compile time
polymorphism, the compiler determines which function call to bind to the object after
deducing it at runtime.
A. Function Overriding
Function Overriding occurs when a derived class has a definition for one of the member
functions of the base class. That base function is said to be overridden.
Function overriding
Explanation
Runtime Polymorphism with Data Members
Runtime Polymorphism cannot be achieved by data members in C++. Let’s see an
example where we are accessing the field by reference variable of parent class which
refers to the instance of the derived class.
• C++
// Driver code
int main(void)
{
Animal d = Dog(); // accessing the field by reference
// variable which refers to derived
cout << d.color;
}
OutputBlack
We can see that the parent class reference will always refer to the data member of the
parent class.
B. Virtual Function
A virtual function is a member function that is declared in the base class using the
keyword virtual and is re-defined (Overridden) in the derived class.
Some Key Points About Virtual Functions:
• Virtual functions are Dynamic in nature.
• They are defined by inserting the keyword “virtual” inside a base class and are
always declared with a base class and overridden in a child class
• A virtual function is called during Runtime
Below is the C++ program to demonstrate virtual function:
• C++
public:
// virtual function
virtual void display()
{
cout << "Called virtual Base Class function"
<< "\n\n";
}
void print()
{
cout << "Called GFG_Base print function"
<< "\n\n";
}
};
public:
void display()
{
cout << "Called GFG_Child Display Function"
<< "\n\n";
}
void print()
{
cout << "Called GFG_Child print Function"
<< "\n\n";
}
};
// Driver code
int main()
{
// Create a reference of class GFG_Base
GFG_Base* base;
GFG_Child child;
base = &child;
In C++, Aggregation is used to represent the ‘HAS-A’ relationship between two objects.
It is a type of association. If in a process, one class defines another class as any entity
reference then it is known as Aggregation. With the help of aggregation, you can also
reuse the class.
Let’s understand through an example between a person and the home address. This
address may belong to other persons as well. The address existed before the man and
will exist for forever. The person knows where he lives but the address does not contain
any information about what person lives. It is an example of an aggregate relationship.
Syntax:-
To put it short, aggregation is a ‘HAS-A’ relationship between the objects of 2 individual
classes. Aggregation restricts some situations of associations.
Class ClassPart
{
//instance variables
//instance methods
}
class Tech
{
ClassPart* partclass;
}
In the above, the Tech class represents the class that is a container class for other
ClassPart. And it is included in the object of the Tech class. The Tech class’s each
object holds a reference pointer to the object of the ClassPart.
In the program, Aggregation helps to represent HAS-A relation between the objects of 2
individual classes. Aggregation is more restrictive compared to the association.
Aggregation helps in making your program code more readable and understandable to
represent the relation. Using a pointer variable, you can refer to the object of one class
in the container class object.
Below are the points which will help you to understand the implementation of
aggregations:-
Aggregation Association
Diamond shape structure is used next to the Line segment is used between the
assembly class. components or the class
Output:
The C++ interfaces are implemented using abstract classes and these abstract
classes should not be confused with data abstraction which is a concept of keeping
implementation details separate from associated data.
A class is made abstract by declaring at least one of its functions as pure virtual
function. A pure virtual function is specified by placing "= 0" in its declaration as follows
−
class Box {
public:
// pure virtual function
virtual double getVolume() = 0;
private:
double length; // Length of a box
double breadth; // Breadth of a box
double height; // Height of a box
};
The purpose of an abstract class (often referred to as an ABC) is to provide an
appropriate base class from which other classes can inherit. Abstract classes cannot be
used to instantiate objects and serves only as an interface. Attempting to instantiate an
object of an abstract class causes a compilation error.
Classes that can be used to instantiate objects are called concrete classes.
Consider the following example where parent class provides an interface to the base
class to implement a function called getArea() −
#include <iostream>
using namespace std;
// Base class
class Shape {
public:
// pure virtual function providing interface framework.
virtual int getArea() = 0;
void setWidth(int w) {
width = w;
}
void setHeight(int h) {
height = h;
}
protected:
int width;
int height;
};
// Derived classes
class Rectangle: public Shape {
public:
int getArea() {
return (width * height);
}
};
int main(void) {
Rectangle Rect;
Triangle Tri;
Rect.setWidth(5);
Rect.setHeight(7);
// Print the area of the object.
cout << "Total Rectangle area: " << Rect.getArea() << endl;
Tri.setWidth(5);
Tri.setHeight(7);
return 0;
}
When the above code is compiled and executed, it produces the following result −
You can see how an abstract class defined an interface in terms of getArea() and two
other classes implemented same function but with different algorithm to calculate the
area specific to the shape.
Designing Strategy
An object-oriented system might use an abstract base class to provide a common and
standardized interface appropriate for all the external applications. Then, through
inheritance from that abstract base class, derived classes are formed that operate
similarly.
The capabilities (i.e., the public functions) offered by the external applications are
provided as pure virtual functions in the abstract base class. The implementations of
these pure virtual functions are provided in the derived classes that correspond to the
specific types of the application.
This architecture also allows new applications to be added to a system easily, even
after the system has been defined.
An interface can only inherit from With the Extended keyword, an abstract class
another interface. can enforce an interface and inherit from
another class.
Use of the implements keyword is Use the extends keyword to inherit from an
required in order to implement an abstract class.
interface.