OOP Lecture Notes: Concepts & Legacy Systems
OOP Lecture Notes: Concepts & Legacy Systems
Lecture Notes:
Drafted by :
Dr. J Sirisha Devi (IARE10566)
Associate Professor
Contents 1
1 OBJECT-ORIENTED CONCEPTS 1
1.1 Objects . . . . . . . . . . . . . . . . . . . . .. . . . . . . . . . . . . . . . . . . 1
1.2 Legacy systems . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
1.3 Procedural versus Object-oriented programming . . . . . . . . . . . . . . . 2
1.4 Top-down and bottom-up approaches . . . . . . . . . . . . . . . . . . . . . 3
1.5 Benefits of OOP . . . . . . . .. . . . . . . . . . . . . . . . . . . . . . . . . . . 4
1.6 Applications of OOP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.7 Features of OOP. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.7.1 Inheritance. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.7.2 Encapsulation. . . . . . . . .. . . . . . . . . . . . . . . . . . . . . 6
1.7.3 Abstraction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.7.4 Polymorphism. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.7.5 Method Overriding. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.7.6 Method Overloading. . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
2 ABSTRACTION 9
2.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.2 Layers of Abstraction. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.2.1 Physical or Internal level . . . . . . . . . . . . . . . . . . . . . . . . . 9
2.2.2 Logical or Conceptual level . . . . . . . . . . . . . . . . . . . . . . . . 10
2.2.3 View or External level . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
2.3 Forms of Abstraction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
2.4 Abstraction Mechanism . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
3 CLASSES AND OBJECTS 12
3.1 Classes and objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
3.2 Object data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
3.3 Object behaviors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
3.4 Creating Objects. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
3.5 Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
3.6 Methods. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
3.7 Messages. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
3.8 Creating Class Diagrams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
3.9 Class Diagram Example: GUI. . . . . . . . . . . . . . . . . . . . . . . . . . . 20
3.10 Access Specifiers. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
3.11 Accessing Members and Methods. . . . . . . . . . . . . . . . . . . . . . . . . 20
3.11.1 Private Access Modifier. . . . . . . . . . . . . . . . . . . . . . . . . . . 23
3.11.2 Default Access Modifier. . . . . . . . . . . . . . . . . . . . . . . . . . . 24
3.11.3 Protected Access Modifier. . . . . . . . . . . . . . . . . . . . . . . . . . 24
3.11.4 Public Access Modifier. . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
3.12 Static Member. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
3.13 Accessing Static Members without any Object. . . . . . . . . . . . . . . . . .. 28
3.14 Static Methods. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
4 SPECIAL MEMBER FUNCTIONS AND OVERLOADING 30
4.1 Constructors and Destructors. . . . . . . . . . . . . . . . . . . . . . . . . . . 30
4.2 Need for Constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
4.3 Types of Constructors. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
4.3.1 Copy Constructor. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31
4.3.2 Dynamic Constructor. . . . . . . . . . . . . . . . . . . . . . . . . . . . 32
4.3.3 Parameterized Constructor. . . . . . . . . . . . . . . . . . . . . . . . . 33
4.4 Destructors with Static Members. . . . . . . . . . . . . . . . . . . . . . . . . 35
4.5 Virtual Destructors. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
MODULE – I
1. OBJECT-ORIENTED CONCEPTS
1.1 Objects
As the name object-oriented implies, objects are key to understanding object-oriented technology. You
can look around you now and see many examples of real-world objects: your dog, your desk, your
television set, your bicycle.
These real-world objects share two characteristics: they all have state and they all have behavior. For
example, dogs have state (name, color, breed, hungry) and dogs have behavior (barking, fetching, and
slobbering on your newly cleaned slacks). Bicycles have state (current gear, current pedal cadence, two
wheels, number of gears) and behavior (braking, accelerating, slowing down, changing gears).
Software objects are modeled after real-world objects in that they, too, have state and behavior. A
software object maintains its state in variables and implements its behavior with methods.
Definition: An object is a software bundle of variables and related methods.
Rip-and-replace and other modernization efforts can be costly in terms of both time and money. In
fact, the change management challenges of replacing established systems that still work well can be
so daunting that many organizations find themselves embracing the old adage, “If it’s not broke, don’t
fix it.”
Legacy platforms and applications often remain operational because they are deeply embedded in an
organization’s business processes. Some examples include:
• Windows XP: Despite Microsoft ending official support for Windows XP in 2014, there are
still instances of businesses and industries using it, often because of application compatibility
issues.
• Older Database Systems: Some companies still rely on old versions of Oracle Database,
Microsoft SQL Server, or IBM DB2 databases because migration to a new database
management system (DBMS) could be costly and time-consuming.
• Legacy Enterprise Resource Planning (ERP) Systems: Older versions of ERP systems like SAP
R/3 or Oracle E-Business Suite can still be found running in some organizations.
• Medical Systems: Devices like MRI machines, ultrasound machines, and other diagnostic
equipment often run on older operating systems or software because of their long lifespan and
high cost of replacement.
• Industrial Control Systems: Many factories and utilities are still using Supervisory Control and
Data Acquisition (SCADA) systems that are decades old.
1
• Point of Sale Systems: Some smaller retail establishments still use older point-of-sale (POS)
systems because they still work, and it’s not worth the cost to upgrade them.
• Bank ATM Software: Some ATMs still run on Windows XP Embedded.
• Older Office Software: Some businesses might still use older versions of Microsoft Office
because they rely on macros and plugins that aren’t compatible with newer versions of the
productivity suite.
• Legacy Telecommunication Systems: Many businesses around the world still rely on
older PBX systems for telephony instead of adopting newer VoIP services.
• Aircraft Systems: Avionics and other in-flight systems sometimes run on legacy software and
hardware because of long testing and certification cycles.
Legacy programming languages are not as popular as they once were, but their use is so ingrained in
certain systems and applications that it’s too complicated to replace them.
For example, many automated teller machines (ATMs) today interface with backend banking systems
that still process transactions on mainframes running COBOL.
Completely phasing out COBOL has been a challenge due to the complexities and high costs of data
migration and the dwindling number of COBOL programmers who would know how to transition these
legacy systems to modern platforms.
Object-oriented programming can be defined as a programming model which is based on the concept
2
of objects. Objects contain data in the form of attributes and code in the form of methods. In object-
oriented programming, computer programs are designed using the concept of objects that interact with
the real world. Object-oriented programming languages are various but the most popular ones are class-
based, meaning that objects are instances of classes, which also determine their types.
Below are some of the differences between procedural and object-oriented programming:
3
In this design, individual parts of the system are specified in detail. The parts are linked to form larger
components, which are in turn linked until a complete system is formed. Object-oriented language such
as C++ or Java uses a bottom-up approach where each object is identified first.
Advantage:
• Make decisions about reusable low-level utilities then decide how they will be put together to
create high-level construct. ,
The contrast between Top-down design and bottom-up design.
4
• OOP language allows to break of the program into bit-sized problems that can be solved easily
(one object at a time).
• The new technology promises greater programmer productivity, better quality of software, and
lesser maintenance costs.
• OOP systems can be easily upgraded from small to large systems.
• It is possible that multiple instances of objects co-exist without any interference,
• It is very easy to partition the work in a project based on objects.
• It is possible to map the objects in the problem domain to those in the program.
• The principle of data hiding helps the programmer build secure programs that cannot be invaded
by the code in other parts of the program.
• By using inheritance, we can eliminate redundant code and extend the use of existing classes.
• Message passing techniques are used for communication between objects which makes the
interface descriptions with external systems much simpler.
• The data-centered design approach enables us to capture more details of the model in an
implementable form.
5
1.7 Features of OOP
1.7.1 Inheritance
In layman’s terms, the attributes that you inherit from your parents are a simple illustration of
inheritance. Classes may inherit characteristics from other classes thanks to inheritance. Parent classes,
in other words, extend properties and behaviors to child classes. Reusability is aided via inheritance.
Prototyping is another name for inheritance in JavaScript. A prototype object serves as a base from
which another object may derive its features and actions. Thus, you may use multiple prototype object
templates to form a prototype chain. Inheritance is passed down from one generation to the next. parent
Consider the application Polygon, which represents several Shapes. We’re expected to make two
distinct sorts of polygons: a Rectangle and a Triangle.
1.7.2. Encapsulation
Encapsulation is the process of enclosing all critical information inside an object and only revealing a
subset of it to the outside world. For example, code inside the class template defines attributes and
behaviors.
The data and methods are then enclosed in the object when it is created from the class. Inside a class,
encapsulation conceals the underlying software code implementation and the internal data of the
objects. Encapsulation necessitates designating certain fields as private while others are made public.
• Methods and attributes only available from other methods in the same class make up the
private/internal interface.
• Methods and attributes that are available from outside the class are known as the public/external
interface.
Encapsulation Demonstration in Real-Time: One of the most practical examples of encapsulation is a
school bag. Our books, pencils, and other items may be kept in our school bag.
1.7.3. Abstraction
Abstraction refers to the user’s interaction with just a subset of an object’s characteristics and
operations. To access a complicated item, abstraction uses simpler, high-level techniques.
• Simple items are used to show complexity.
• Keep complicated information hidden from the user.
6
A Real-Life Example of Abstraction: Abstraction reveals just the most significant facts to the user while
hiding the underlying intricacies. For example, when we ride a bike, we only know how to ride it but
not how it works. We also have no idea how a bike works on the inside.
Advantages of Abstraction
• It simplifies the process of seeing things in their entirety.
• Code duplication is avoided, and reusability is increased.
• Because just the most necessary information is shown to the user, it helps to enhance the
security of an application or software.
1.7.4. Polymorphism
Polymorphism refers to the creation of items that have similar behavior. For example, objects may
override common parent behaviors with particular child behaviors through inheritance. Method
overriding and method overloading are two ways that polymorphism enables the same method to
perform various actions.
Examine how Polymorphism and the actual world are interconnected with examples.
Take, for example, your mobile phone. It has the capability of storing your Contacts. Consider the
following scenario: you wish to store two numbers for one individual. You may do this by storing the
second number under the same name as the first.
Consider the following scenario: you wish to store two numbers for the same individual in an object-
oriented language such as Java. Create a function that will accept as arguments two integers and the
name of the individual to some function void createContact that will be defined later (String name, int
number1, int number2).
Method overriding is used in runtime polymorphism. When a child class overrides a parent class’s
method, the child class might offer an alternative implementation.
Consider a family of three, consisting of the father, mother, and son. The father makes the decision to
teach his kid to shoot. As a result, he brings him to the range with his favorite rifle and teaches him how
to aim and fire at targets. The father, on the other hand, is right-handed, while the kid is left-handed. So
they each have their own way of handling the pistol! Because of their differing orientations, the father
was concerned that he may not be able to teach his son how to shoot.
The son, on the other hand, was astute and chose to flip his father’s hands, putting his dominant hand
on the trigger rather than the father’s. Specifically, the right hand. By significantly changing the learning
process, the son was able to grasp the skill of shooting!
Method overloading is used in compile-time polymorphism. Although two methods or functions may
have the same name, the number of arguments given to the method call may vary. Therefore, depending
on the number of parameters entered, you may obtain different results.
7
With the help of a simple example, it may be comprehended in simple words. A class addition contains
two add() methods, one with arguments int a and int b and the other with three integer parameters, int
a, int b, and int c. As a result, the add() function is considered overloaded.
The amount of arguments given in the method calling statement determines which method is performed.
For example, add(20,30) calls the two-parameter add() function, whereas add(10,20,30) calls the three-
parameter add method.
8
2. ABSTRACTION
2.1 Introduction
Abstraction is the process of hiding the internal details of an application from the outer world.
Abstraction is used to describe things in simple terms. It’s used to create a boundary between the
application and the client programs.
Access specifiers are the main pillar of implementing abstraction. We can use access specifiers to
enforce restrictions on class members. For example:
• Members declared as public in a class can be accessed from anywhere in the program.
• Members declared as private in a class, can be accessed only from within the class. They are not
allowed to be accessed from any part of the code outside the class.
9
2.2.2. Logical or Conceptual Level
This level comprises the information that is actually stored in the database in the form of tables. It
also stores the relationship among the data entities in relatively simple structures. At this level, the
information available to the user at the view level is unknown. We can store the various attributes of
an employee and relationships, e.g. with the manager can also be stored.
10
2.4 Abstraction mechanisms
1. Abstraction using Classes
We can implement Abstraction using classes. The class helps us to group data members and
member functions using available access specifiers. A Class can decide which data member will be
visible to the outside world and which is not.
• Members declared as public in a class can be accessed from anywhere in the program.
• Members declared as private in a class, can be accessed only from within the class.
They are not allowed to be accessed from any part of the code outside the class.
11
MODULE – II
12
The corresponding getter and setter would look like this:
public void setName (String n) {name = n;};
public String getName() {return name;};
Now, when creating an XML attribute called Name, the definition in C# .NET may look something like
this:
Private string strName;
public String Name
{
get
{
return this.strName;
}
set
{
if (value == null) return;
this.strName = value;
}
}
In this approach, the getters and setters are actually properties of the attributes—in this case, Name.
Regardless of the approach, the purpose is the same—controlled access to the attribute.
Note that we are showing only the interface of the methods and not the implementation. The following
information is all the user needs to know to effectively use the methods:
a. The name of the method
b. The parameters passed to the method
c. The return type of the method
In the above figure, the Payroll object contains a method called CalculatePay() that calculates the pay
for a specific employee. Among other information, the Payroll object must obtain the Social Security
number of this employee. To get this information, the payroll object must send a message to the
Employee object (in this case, the getSocialSecurityNumber() method). Basically, this means that the
Payroll object calls the getSocialSecurityNumber() method of the Employee object. The employee
object recognizes the message and returns the requested information.
13
3.4 Creating objects
Classes can be thought of as the templates, or cookie cutters, for objects. A class is used to create an
object.
A class can be thought of as a sort of higher-level data type. For example, just as you create an integer
or a float:
int x;
float y;
you can also create an object by using a predefined class:
myClass myObject;
In this example, the names themselves make it obvious that myClass is the class and myObject is the
object.
Remember that each object has its own attributes (data) and behaviors (functions or routines). A class
defines the attributes and behaviors that all objects created with this class will possess. Classes are
pieces of code. Objects instantiated from classes can be distributed individually or as part of a library.
Because objects are created from classes, it follows that classes must define the basic building blocks
of objects (attributes, behavior, and messages). In short, you must design a class before you can create
an object.
For example, here is a definition of a Person class:
public class Person{
//Attributes
private String name;
private String address;
//Methods
public String getName(){
return name;
}
public void setName(String n){
name = n;
}
public String getAddress(){
return address;
}
public void setAddress(String adr){
address = adr;
}}
14
3.5 Attributes
As you already saw, the data of a class is represented by attributes. Each class must define the attributes
that will store the state of each object instantiated from that class. In the Person class example in the
previous section, the Person class defines attributes for name and address.
3.6 Methods
As you learned earlier in the chapter, methods implement the required behavior of a class. Every object
instantiated from this class has the methods as defined by the class. Methods may implement behaviors
that are called from other objects (messages) or provide the fundamental, internal behavior of the class.
Internal behaviors are private methods that are not accessible by other objects. In the Person class, the
behaviors are getName() , setName() , getAddress() , and setAddress() . These methods allow other
objects to inspect and change the values of the object’s attributes. This is a common technique in OO
systems. In all cases, access to attributes within an object should be controlled by the object itself—no
other object should directly change an attribute of another.
3.7 Messages
Messages are the communication mechanism between objects. For example, when Object A invokes a
method of Object B, Object A sends a message to Object B. Object B’s response is defined by its return
value. Only the public methods, not the private methods, of an object can be invoked by another object.
The following code illustrates this concept:
public class Payroll{
String name;
Person p = new Person();
String = p.setName(“Joe”);
... code
String = p.getName();
}
In this example (assuming that a Payroll object is instantiated), the Payroll object is sending
a message to a Person object, with the purpose of retrieving the name via the getName()
method.
A class represents a concept that encapsulates state (attributes) and behavior (operations). Each attribute
has a type. Each operation has a signature. The class name is the only mandatory information.
15
Class Name:
• The name of the class appears in the first partition.
Class Attributes:
• Attributes are shown in the second partition.
• The attribute type is shown after the colon.
• Attributes map onto member variables (data members) in code.
Class Operations (Methods):
• Operations are shown in the third partition. They are services the class provides.
• The return type of a method is shown after the colon at the end of the method signature.
• The return type of method parameters are shown after the colon following the parameter name.
Operations map onto class methods in code
Class Visibility
The +, - and # symbols before an attribute and operation name in a class denote the visibility of the
attribute and operation.
16
Parameter Directionality
Each parameter in an operation (method) may be denoted as in, out or inout which specifies its
direction with respect to the caller. This directionality is shown before the parameter name.
17
Inheritance (or Generalization):
A generalization is a taxonomic relationship between a more general classifier and a more specific
classifier. Each instance of the specific classifier is also an indirect instance of the general classifier.
Thus, the specific classifier inherits the features of the more general classifier.
• Represents an "is-a" relationship.
• An abstract class name is shown in italics.
• SubClass1 and SubClass2 are specializations of SuperClass.
The figure below shows an example of inheritance hierarchy. SubClass1 and SubClass2 are derived
from SuperClass. The relationship is displayed as a solid line with a hollow arrowhead that points from
the child element to the parent element.
18
Association
Associations are relationships between classes in a UML Class Diagram. They are represented by a
solid line between classes. Associations are typically named using a verb or verb phrase which reflects
the real world problem domain.
Simple Association
• A structural link between two peer classes.
• There is an association between Class1 and Class2
The figure below shows an example of simple association. There is an association that connects the
<<control>> class Class1 and <<boundary>> class Class2. The relationship is displayed as a solid line
connecting the two classes.
Cardinality
Cardinality is expressed in terms of:
• one to one
• one to many
• many to many
19
Aggregation
A special type of association.
• It represents a "part of" relationship.
• Class2 is part of Class1.
• Many instances (denoted by the *) of Class2 can be associated with Class1.
• Objects of Class1 and Class2 have separate lifetimes.
The figure below shows an example of aggregation. The relationship is displayed as a solid line with a
unfilled diamond at the association end, which is connected to the class that represents the aggregate.
Composition
• A special type of aggregation where parts are destroyed when the whole is destroyed.
• Objects of Class2 live and die with Class1.
• Class2 cannot stand by itself.
The figure below shows an example of composition. The relationship is displayed as a solid line with a
filled diamond at the association end, which is connected to the class that represents the whole or
composite.
Dependency
An object of one class might use an object of another class in the code of a method. If the object is not
stored in any field, then this is modeled as a dependency relationship.
• A special type of association.
• Exists between two classes if changes to the definition of one may cause changes to the other
(but not the other way around).
• Class1 depends on Class2
The figure below shows an example of dependency. The relationship is displayed as a dashed line with
an open arrow.
20
The figure below shows another example of dependency. The Person class might have a hasRead
method with a Book parameter that returns true if the person has read the book (perhaps by checking
some database).
Realization
Realization is a relationship between the blueprint class and the object containing its respective
implementation level details. This object is said to realize the blueprint class. In other words, you can
understand this as the relationship between the interface and the implementing class.
For example, the Owner interface might specify methods for acquiring property and disposing of
property. The Person and Corporation classes need to implement these methods, possibly in very
different ways.
21
3.9 Class Diagram Example: GUI
A class diagram may also have notes attached to classes or relationships.
Access specifiers/ modifiers help to restrict the scope of a class, constructor, variable, method, or data
member. It provides security, accessibility, etc to the user depending upon the access modifier used
with the element.
All variables which are defined in a class are known as instance variables as each object of the class
will have its own copy of the variables. Hence the data in various objects are unique and are separate
from one another.
When declaring variables, there are three Access Level Modifiers. These are:
Access specifiers/ modifiers are keywords that can be used to control the visibility of fields, methods,
and constructors in a class. The four access modifiers in Java are public, protected, default, and private.
Four Types of Access Modifiers
• Private: We can access the private modifier only within the same class and not from outside the
class.
• Default: We can access the default modifier only within the same package and not from outside
22
the package. And also, if we do not specify any access modifier it will automatically consider it
as default.
• Protected: We can access the protected modifier within the same package and also from outside
the package with the help of the child class. If we do not make the child class, we cannot access
it from outside the package. So inheritance is a must for accessing it from outside the package.
• Public: We can access the public modifier from anywhere. We can access public modifiers from
within the class as well as from outside the class and also within the package and outside the
package.
Let us see which all members of Java can be assigned with the access modifiers:
Now let us understand the scope of these access modifiers with the help of a table:
• The private access modifier is specified when any member of a class is prefixed with the private
keyword. In comparison with the other access modifiers, this is the most restricted access
modifier.
• When the methods or data members are prefixed with a private access modifier, the visibility of
these methods and data members are restricted so, they can be accessed only within the same
class where they have been declared, they will not be visible to the outside world.
• If we have another class from the same package still, we will not be able to access these methods
or data members. So usually, we keep the class variables and methods as private, which are
intended to be used inside the same class where declared.
23
Let us consider an example where we will consider two classes A1 and A2 within the same package p1.
We will declare a variable and a method as private in class A1 and then try to access these methods and
variables from class A2.
If we make any class constructor private, we cannot create the instance of that class from outside the
class, and hence, from here we can conclude that the private access modifier can be accessed
only within the same class and not from outside the class.
• It is not a keyword. Any Java members such as class or methods or data members when not
specified with any access modifier they are by default considered as default access
modifiers. These methods or data members are only accessible within the same package and
they cannot be accessed from outside the package. It provides more visibility than a private access
modifier. However this access modifier is more restricted than protected and public access
modifiers.
Here, we have two different packages p1 and p2. In the p1 package, we have class A1 where we declare
a default variable and a default method. Now we are trying to access this variable and method from
outside the package that is from package p2 which has a class A2.
When we try to access these variables and methods from outside the package we get a Compile time
error. Hence, we conclude that the default access modifier members can be accessed only within the
same package and cannot be accessed from outside the package. And they have more visibility than
private access modifier but is more restricted than protected and public access modifiers.
• It is a keyword. This access modifier is used to access the methods or data members of a
class within the same package as well as outside the package but only through inheritance.
The protected access modifier has more accessibility than private and default access modifiers.
But it has less visibility than the public access modifier.
Here we have two packages p1 and p2. In package p1 we have class A1 where we have declared a
protected test method. In package p2 we are inheriting the members of class A1 inside class A2 with
the help of extending keywords and creating a relationship between the two classes. We can also say
that class A1 is the parent class or the superclass and class A2 is the child class or the subclass
respectively.
When we inherit the members of class A1 inside class A2, with the help of a protected access
modifier we can access the members of class A1 of package p1 from class A2 of the different package
p2.
24
So here we get the output as Hi I’m from a protected method.
Hence, we can conclude that the methods, variables, and data members of a class prefixed with
a protected access modifier can be accessed within the same package as well as can be accessed
from outside the package but only with the help of inheritance.
It is a keyword. If a class member like variable, method, or data members are prefixed with a public
access modifier, then they can be accessed from anywhere inside the program. That is, they can be
accessed within the same class as well as from outside the different classes.
It also includes access within the same package and also from outside the package. The members like
variables, methods, and other data members can be accessed globally.
Using public access modifiers we can provide access to the members most simply. There are no
restrictions on public access modifier members. Hence, it has the widest accessibility or visibility scope
as compared to the rest of the access modifiers.
Here in this example, we have two different packages p1 and p2. In p1 we have a class a1 where we
have declared a variable and a method prefixed public keyword. And in the p2 package, we have a class
A2 from where we are trying to access the members of class A1 without inheritance.
Here we get the output as 10 and Hi I’m from the public method.
So from the above example, we can conclude that public access modifier members can be accessed
from anywhere, within the same class as well as from outside the class. And also can be accessed within
the same package and also from outside a package.
Example:
Here are examples of access modifiers in Java:
// Public access modifier
public class PublicClass {
public int publicField;
public void publicMethod() {
// code here
}
}
// Protected access modifier
protected class ProtectedClass {
protected int protectedField;
protected void protectedMethod() {
// code here
}
}
// Default (package-private) access modifier
class DefaultClass {
25
int defaultField;
void defaultMethod() {
// code here
}
}
// Private access modifier
class PrivateClass {
private int privateField;
private void privateMethod() {
// code here
}
}
• Only one copy of that member is created for the entire class and is shared by all the objects of
that class, no matter how many objects are created.
• It is initialized before any object of this class is created, even before the main starts.
• It is visible only within the class, but its lifetime is the entire program.
Syntax:
static data_type data_member_name;
// C++ Program to demonstrate the working of static data member
#include <iostream>
using namespace std;
class A {
public:
A()
{
cout << "A's Constructor Called " <<
endl;
}
};
class B {
static A a;
public:
B()
{
cout << "B's Constructor Called " <<
endl;
}
};
26
// Driver code
int main()
{
B b;
return 0;
}
class A {
int x;
public:
A()
{
cout << "A's constructor called " <<
endl;
}
};
class B {
static A a;
public:
B()
{
cout << "B's constructor called " <<
endl;
}
static A getA()
{
return a;
}
};
// Driver code
int main()
{
27
B b;
A a = b.getA();
return 0;
}
Output
Compiler Error: undefined reference to `B::a'
class A {
int x;
public:
A()
{
cout << "A's constructor called " <<
endl;
}
};
class B {
static A a;
public:
B()
{
cout << "B's constructor called " <<
endl;
}
static A getA()
{
return a;
}
};
// Definition of a
A B::a;
// Driver code
int main()
28
{
// static member 'a' is accessed
// without any object of B
A a = B::getA();
return 0;
}
Output
A's constructor called
The static keyword is used to construct methods that will exist regardless of whether or not any instances
of the class are generated. Any method that uses the static keyword is referred to as a static method.
// Method body.
className.methodName();
29
MODULE – III
ClassName()
{
//Constructor's Body
}
Destructor:
Like a constructor, Destructor is also a member function of a class that has the same name as the class
name preceded by a tilde(~) operator. It helps to deallocate the memory of an object. It is called while
the object of the class is freed or deleted. In a class, there is always a single destructor without any
parameters so it can’t be overloaded. It is always called in the reverse order of the constructor. if a class
is inherited by another class and both the classes have a destructor then the destructor of the child class
is called first, followed by the destructor of the parent or base class.
Syntax:
~ClassName()
{
//Destructor's Body
}
Note: If we do not specify any access modifiers for the members inside the class then by default the
access modifier for the members will be Private.
30
6. Constructor can be overloaded. While it can’t be overloaded.
7. The constructor’s name is same as the class Here, its name is also same as the class name
name. preceded by the tiled (~) operator.
8. In a class, there can be multiple constructors.
While in a class, there is always a single
destructor.
9. There is a concept of copy constructor which Here, there is no copy-destructor concept.
is used to initialize an object from another
object.
10. They are often called in successive order. They are often called in reverse order of
constructor.
The purpose of a constructor is to construct an object and assign values to the object's members. A
constructor takes the same name as the class to which it belongs and does not return any values.
Destructors are usually used to deallocate memory and do other cleanup for a class object and its class
members when the object is destroyed. A destructor is called for a class object when that object passes
out of scope or is explicitly deleted.
Copy constructor is used to initialize the members of a newly created object by copying the members
of an already existing object.
Sample(Sample &t)
{
id=t.id;
}
The process of initializing members of an object through a copy constructor is known as copy
initialization.
It is also called member-wise initialization because the copy constructor initializes one object with the
existing object, both belonging to the same class on a member-by-member copy basis.
The copy constructor can be defined explicitly by the programmer. If the programmer does not define
the copy constructor, the compiler does it for us.
31
Characteristics of Copy Constructor
1. The copy constructor is used to initialize the members of a newly created object by copying the
members of an already existing object.
Sample(Sample &t)
{
id=t.id;
}
3. The process of initializing members of an object through a copy constructor is known as copy
initialization.
4. It is also called member-wise initialization because the copy constructor initializes one object with
the existing object, both belonging to the same class on a member-by-member copy basis.
5. The copy constructor can be defined explicitly by the programmer. If the programmer does not
define the copy constructor, the compiler does it for us.
In simple terms, a Dynamic constructor is used to dynamically initialize the objects, that is memory is
allocated at run time.
We will dynamically allocate memory to the data members inside the default constructor of class A as
well as a parameterized constructor of class A and check the output.
#include <iostream>
using namespace std;
class A
{
int *value;
public:
A()//Default constructor
{
value = new int; //Memory allocation at run time
32
*value = 1729;
}
A(int p_value) //Parameterised constructor
{
value = new int; //Memory allocation at run time
*value= p_value+1;
}
void display()
{
cout<< *value <<endl;
}
~A()
{
delete value ;
}
};
int main()
{
A obj1, obj2(7225);
cout<<"The value of object obj1 is: ";
obj1.display();// Calling default constructor
cout<<"\nThe value of object 0bj2 is: ";
obj2.display();// calling parameterised constructor
return 0;
}
Output:
During the initialization of an object, which constructor should get invoked depends upon the
parameters one passes. For example when we create object like namesClass n1=new
namesClass("Krishna"); then the new keyword invokes parameterized constructor with string parameter
(namesClass(String)) after object initialization.
33
public class studentDetails {
// Default constructor created by programmer
studentDetails(){
System.out.println("Default constructor");
}
Output
Default constructor
34
Parameterized constructor one String argument. Name: Krishna Das
Parameterized constructor with one string and one integer argument.
Name:Pawan Singhania Age:21
Think of static members as being shared across all objects (instances) of the class. Only one copy of a
static member exists, no matter how many objects (instances) you have created. Static members exist,
even if no objects of the class have been created. Static members are part of the class but are not bound
to individual class members.
The lifetime (or storage duration) of static members is, well, static. The storage for a static member is
allocated when the program begins and is deallocated when the program ends, just as static global
variables are. That’s what is meant by static storage duration.
Now, if you define the static member as thread_local, then there is one per thread, springing into
existence when the thread starts, and ceasing to exist with the thread terminates. But the static member
is still independent of the number of object instances, and has nothing to do with the object destructor
being called.
int main()
35
{
derived *d = new derived();
base *b = d;
delete b;
getchar();
return 0;
}
Output
Constructing base
36