OBJECT-ORIENTED PROGRAMMING
I Semester
Dr.
D.SREELAKSHMI
Assistant Professor
CSE (AI & ML) Dept.
Syllabus-OOPS
UNIT NAME
II Classes and objects
COs Course outcomes
CO2 Recall the concepts of special member functions for writing robust, efficient,
and maintainable code
1) Matt Weisfeld, “The Object-Oriented Thought Process”, Addison Wesley Object
Technology Series, 4 th Edition, 2013.
2) Timothy Budd, “An introduction to Object Oriented Programming”, Addison Wesley
Object Technology Series, 3rd Edition, 2021.
Syllabus-Unit II
Classes and objects
Object data
Object behaviors
Creating objects
Attributes
Methods
Messages
Creating class diagrams
Access specifiers and initialization of class members
Accessing members and methods
Access specifiers-private, public, protected
Memory allocation
Static members
Static methods
Object data
Objects are the building blocks of an OO program.
Object behaviors
The behavior of an object is what the object can do.
In procedural languages the behavior is defined by
procedures, functions, and subroutines.
In OO programming terminology these behaviors are
contained in methods, and you invoke a method by
sending a message to it.
The State of an object
Represented by the data fields of the object with their
current values.
The state of an object is also know as its properties and
attributes.
A point object , ex: has a data field X and Y that
characterizes a point.
A rectangle object has the data fields width and height, that
characterizes a rectangle.
The behavior of an object
Defined by methods of an object
The behavior of an object is also known as its actions.
To invoke /call a method on an object is to ask the object
to perform an action.
Ex: str.charat(2)
Ex: we can define the following methods for a circle object
getArea(): returns the area of the circle
getPerimeter(): returns the perimeter of the circle
setRadius(radius):sets/changes the radius of the circle.
The identity of an object:
What an makes an object unique
Point p1=new point(0,1);
Point p2=new point(0,1);
System.out.println(p1= =p2);
Address in the p1 and p2 are different, in this case the
identity of the object is address of the object in the memory.
State and behavior of the object:
These two are of same class, so data fields and methods are
same, if the methods are same then their behavior is same.
When they have same data fields i.e X and Y and the values
are also same. The state is same because the state represented
by data fields.
Class
A class defines the data fields and actions of an object
To create an object we need a templet/blueprint that
defines the data fields and methods that this object will
have.
Object is an instance of the class
Objects of the same type are created/instantiated from the
same class.
A Java class uses variables to define the data fields and
methods to define the actions. There are special methods
called constructors.
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;
}
}
Creating objects
Constructor is a method used to create objects.
It is designed to do initializing actions, such as initializing the
data fields of an object. we don’t want do any thing in the
constructor.
Ex:
Point p1= new point(0,1);//a constructor
public Point(int x, int y)
{
this.x=x;
this.y=y;
}
Default constructor
If we create a class without defining a constructor, java
automatically creates a default constructor that takes no
parameters and we be able to use it to create objects of the
class.
Creating objects in Java
Java new Operator
class_name object_name = new class_name()
Java Class.newInstance() method
public T newInstance() throws IllegalAcccessException, InstantiationException
Java newInstance() method of constructor
public T newInstance(Objects...initargs)
Java Object.clone() method
protected Object clone() throws CloneNotSupportedException
Java Object Serialization and Deserialization
public final void writeObject(Object obj) throws IOException
Creating objects in Java
Attributes:
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.
The Person class defines attributes for name and address.
Messages are the communication mechanism between
objects.
For example, when Object A invokes a method of Object
B, Object A is sending 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.
Creating class diagrams
The UML Class diagram is a graphical notation used to
construct and visualize object oriented systems.
A class diagram in the Unified Modeling Language
(UML) is a type of static structure diagram that describes
the structure of a system by showing the system's:
• classes,
• their attributes,
• operations (or methods),
• and the relationships among objects.
UML Class Notation
A class represent a concept which encapsulates state
(attributes) and behavior (operations).
Each attribute has a type. Each operation has
a signature. The class name is the only mandatory
information.
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.
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.
Perspectives of Class Diagram
A diagram can be interpreted from various perspectives:
Conceptual: represents the concepts in the domain
Specification: focus is on the interfaces of Abstract Data
Type (ADTs) in the software
Implementation: describes how classes will implement their
interfaces
Relationships between classes
Simple Association
Cardinality
Aggregation
Composition
Dependency
class diagram-order system
Benefits of class diagrams
Class diagrams are simple, fast to read and gives a sense
of orientation.
They are the foundation for creating the systems.
They will provide detailed insight into the structure of
your systems.
Create complete charts that highlight specific code needed
to be programmed and executed to the defined structure.
Provide an implementation-independent explanation of
types used in a system that is later passed to its component.
Private
Public
Protected
Default
Access specifiers
The access modifiers can be used to define the level of
accessibility of either the members in the class/interface or
the level of accessibility of a class/interface in a package.
Using the access modifiers we can define the scope of a
class/interface or its members and provide security.
There are four levels of access modifiers/specifiers with three
keywords,
i. Public(class, interface, variables, methods and constructors)
ii. Private(variables, methods and constructors)
iii.Protected(variables, methods and constructors)
iv.Default(class, interface, variables methods and constructors)
Private: The access level of a private modifier is only within the
class. It cannot be accessed from outside the class.
Default: The access level of a default modifier is only within the
package. It cannot be accessed from outside the package. If you
do not specify any access level, it will be the default.
Protected: The access level of a protected modifier is within the
package and outside the package through child class. If you do
not make the child class, it cannot be accessed from outside the
package.
Public: The access level of a public modifier is everywhere. It
can be accessed from within the class, outside the class, within
the package and outside the package.
Private
class A{
private int data=40;
private void msg()
{
System.out.println("Hello java");
}
}
public class Simple{
public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
}
}
Default
//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
}
Protected
//save by A.java
package pack;
public class A{
protected void msg()
{System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
Public
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");
}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Example
package1 package2
A D
int x=10
B C E
Memory Allocation for Objects
The memory allocation for an object means it is the
process to reserve the memory block in the memory of the
computer for storing an object during the runtime.
Objects are also known as instances. These instances
represent real-world entities such as a person, a car, or a
bank account.
When an object is created, the memory needs to be
allocated to store its data members (variables) and
member functions (methods) so that these objects can be
accessed and manipulated during program execution.
How Does Memory Allocation for Objects Work?
The memory for the object in two steps. These two steps are
as follows.
1. Memory Allocation:
In object-oriented programming (OOP), memory must be
allocated to store its data member and function.
The amount of memory required for an object depends on the
size and type of its data members and the size and complexity
of its member functions
•Stack Memory Allocation: the stack is used to store the
order of method execution and local variables
•Heap Memory Allocation: the heap memory stores the
objects and it uses dynamic memory allocation and
deallocation
2. Memory deallocation:
Memory deallocation is necessary to free up the memory
occupied by the object once the object is no longer needed.
In Java and C#, memory deallocation is done automatically
by a process called garbage collection,
In other languages, such as C++, deallocation done manually
using techniques such as delete (for single objects) or delete[]
(for arrays).
Implications/Advantages
of Memory Allocation
1. Memory Efficiency
2. Memory Overhead
3. Memory leaks
4. Lifetime and Scope of Objects
5. Memory Fragmentation
Implications/Advantages
of Memory Allocation
1. Memory Efficiency:
When the programmer allocates memory inefficiently manner
then it has a great impact on the performance of the program.
When we compare the memory allocation in the stack area in
comparison to the heap area, the stack area is very fast and
inefficient in memory management. In the stack area, the memory
is managed automatically with the help of a compiler;
on the other hand in, the heap area requires memory to be
managed manually, which can be error-prone and may result in
memory leaks if not handled properly.
Implications/Advantages
of Memory Allocation
2. Memory Overhead:
The memory allocation in the object can lead to overhead in the
memory. This means the program consumes some extra memory
space due to the memory management mechanism.
For example, some languages, such as C ++, require explicit
memory deallocation using delete or delete[] statements, which
can introduce code complexity and maintenance overhead.
Garbage collection in languages like Java and C# can also
introduce overhead in terms of runtime performance as the
garbage collector needs to periodically scan and clean up objects
that are no longer needed.
Understanding and managing memory overhead is important to
ensure efficient memory usage in a program.
Implications/Advantages
of Memory Allocation
3. Memory leaks:
When the programmer tries to allocate and deallocate the
memory improperly, there is a chance of memory leaks. It also
occurs when the programmer allocates the memory but does not
deallocate the memory in a proper way.
It occupies the memory indefinitely, but this memory was not
available for the other part of the program.
A memory leak can also degrade the performance of the
program over time, and after some time, it shows an error like
insufficient memory space. So properly managing memory
allocation and deallocation is essential to prevent memory leaks
and ensure the efficient use of memory in a program.
Implications/Advantages
of Memory Allocation
4. Lifetime and Scope of Objects:
The object that is allocated over the stack has a limited lifetime.
After completion of the lifetime of the object, it is automatically
deallocated when they go out of scope.
The objects are allocated on the heap, which have longer
lifetimes, and the programmer has to deallocate the memory
manually.
Understanding the lifetime and scope of objects is important
for managing memory efficiently and avoiding dangling pointers
or references, which can result in unexpected behavior and bugs
in a program.
Implications/Advantages
of Memory Allocation
5. Memory Fragmentation:
When the memory is allocated and deallocated in a contiguous
manner, and it leaves gaps of unused memory that are too small to
be used for new allocations, then the fragmentation of memory
occurs.
It causes inefficient memory usage and reduced performance.
Some languages and memory allocation techniques, such as
garbage collection in Java and C#, can help mitigate memory
fragmentation.
However, in some languages like C++, the memory is managed by
the programmer manually, and it can result in fragmentation if not
handled properly. Understanding and managing memory
fragmentation is important to ensure efficient memory allocation
and usage in a program.
Parameter Stack Memory Heap Space
Application It stores items that have a very It stores objects and Java Run time
short life such as methods, Environment (JRE) classes.
variables, and reference
variables of the objects.
Ordering It follows the LIFO order. It does not follow any order because
it is a dynamic memory allocation
and does not have any fixed pattern
for allocation and deallocation of
memory blocks.
Flexibility It is not flexible because we It is flexible because we can alter the
cannot alter the allocated memory. allocated memory.
Efficiency It has faster access, allocation, It has slower access, allocation, and
and deallocation. deallocation.
Memory Size It is smaller in size. It is larger in size.
Options Used We can increase the stack We can increase or decrease the heap
size by using the JVM memory size by using the -Xmx and
option -Xss. -Xms JVM options.
Visibility or Scope The variables are visible It is visible to all threads.
only to the owner thread.
Generation of When a thread is created, To create the heap space for the
Space the operating system application, the language first calls the
automatically allocates the operating system at run time.
stack.
Distribution Separate stack is created It is shared among all the threads.
for each object.
Exception Throws JVM throws the JVM throws
java.lang.StackOverFlow the java.lang.OutOfMemoryError if
Error if the stack size is the JVM is unable to create a new
greater than the limit. To native method.
avoid this error, increase
the stack size.
Allocation/ It is done automatically It is done manually by
Deallocation by the compiler. the programmer.
Cost Its cost is less. Its cost is more in
comparison to stack.
Implementation Its implementation Its implementation is easy.
is hard.
Order of Memory allocation Memory allocated
allocation is continuous. in random order.
Thread-Safety It is thread-safe because It is not thread-safe, so
each thread has its own properly synchronization of
stack. code is required.
Static member and method
Static variables and methods belong to a class and are called
with the Class Name rather than using object variables, like
ClassName.methodName();
There is only one copy of a static variable or method for the
whole class.
For example, the main method is static because there should
only be 1 main method.
Static methods can be public or private.
The static keyword is placed right after the public/private
modifier and right before the type of variables and methods
in their declarations.
Static methods only have access to other static variables and
static methods.
Static methods cannot access or change the values of
instance variables or the this reference (since there is no
calling object for them),
Static methods cannot call non-static methods.
Non-static methods have access to all variables (instance or
static) and methods (static or non-static) in the class.
The static method does not have access to the instance
variable
The JVM runs the static method first, followed by the creation
of class instances. Because no objects are accessible when the
static method is used. A static method does not have access to
instance variables. As a result, a static method can’t access a
class’s instance variable.
In both static and non-static methods, static methods are
directly accessed.
Instance Methods Static Methods
It doesn’t require an object of the
It requires an object of the class.
class.
It can access all attributes of a It can access only the static attribute
class. of a class.
The methods can be accessed The method is only accessed by
only using object reference. class name.
Syntax: Objref.methodname() Syntax: className.methodname()
It’s an example of pass-by-value It is an example of pass-by-
programming. reference programming.