0% found this document useful (0 votes)
0 views

Lecture#5 Classes

The document provides an overview of Object-Oriented Programming (OOP) concepts, focusing on classes and objects, their attributes, behaviors, and interactions. It explains key principles such as encapsulation, data hiding, and access specifiers in Java, along with examples of defining classes and creating objects. Additionally, it highlights the differences between classes and structures, and the handling of object references in Java.

Uploaded by

qmumer7
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Lecture#5 Classes

The document provides an overview of Object-Oriented Programming (OOP) concepts, focusing on classes and objects, their attributes, behaviors, and interactions. It explains key principles such as encapsulation, data hiding, and access specifiers in Java, along with examples of defining classes and creating objects. Additionally, it highlights the differences between classes and structures, and the handling of object references in Java.

Uploaded by

qmumer7
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 38

Glory be to you, we have no knowledge except what you have

taught us. Verily, it is You, the All Knower, the All-Wise.


Q[2:32]
Object-Oriented Programming
Terminology
• Class: an abstract data-type or a user-defined data type,
similar to a struct (allows bundling of related variables)

• Object: an instance of a class, in the same way that a


variable can be an instance of a struct
Some Daily Life Examples of Objects
Object may represent a person, thing or place in real
world……………..
What is object? An object is a collection of
data/atttributes and functions/behaviors.

Car
• Attributes:
• Gas in tank
Bank Account • Mileage
• Wheels
• Attributes:
• Behavior
• balance
• Accelerate
• Behavior
• Apply Brakes
• Deposit
• Load fuel
• Withdraw
• Check fuel
• Check balance
Objects Interact with each other

Get Loan

Bank Customer

Deduct Zakat Deposit


Withdraw

Bank Account
What is object? An object is a collection of
data/atttributes and functions/behaviors.

Example: A person as an Object


• A person can be an example of an object. It has some
properties or characteristics or attributes that describe
what it is. Some properties of Person object can be as
follows:
• Attributes: Name, Age, Height

• The Person object also has some behaviors or functions


that describe what it can do. Some functions of Person
object can be as follows:
• Behaviours: Walk , Talk, Eat
Object in Object Oriented Programming
 In OOP, an object is a collection of data and functions.

 The main aim of OOP is to bind together the data and the functions (that
operate on them) so that no other part of the code can access this data
except that function.

double width;
double length; Encapsulation refers
Data to the combining of
data and code into a
single object
displayWidth(){}
displayLength(){}
displayArea(){}
Functions Rectangle
Object
Classes and Objects
• A class is like a blueprint and objects are like houses
built from the blueprint.
• An object is an instance of a class
• A single class can have multiple instances
Class & Object in Object Oriented
Programming
Object:
•In OOP an object is a collection of data and functions.
•In OOP, programs are written on the basis of objects.
We visualize our programming problems in the form of objects and their
interactions.
To create different objects, classes are used.

Class:
- Classes are pieces of code blueprints which are used to
create objects.
- Class: It is the Collection of data (atttributes) and functions
(behaviors) related to that object .

-Class is a user-defined data type, which holds its data members


and member functions together. 8
-The created class can be accessed and used by creating an
instance/object of that class.
Object Oriented Programming

• Data members are the data variables.


• Member functions are the functions used to manipulate
these data variables.
• Together these data members and member functions
defines the behavior of the objects in a Class.

• When a class is defined, no memory is allocated but


when it is initalized (i.e. an object is created) memory is
allocated.
Syntax for defining a Class

• Format:
public class ClassName
{
variable declaration;
methods declaration;
}

A class is defined in JAVA using keyword class


followed by the name of class. The body of
class is defined inside the curly brackets.
Class Example

Public class Rectangle


{
private int width;
Data (attributes)
private int length;

public displayWidth(){}
public displayLength(){} Functions
public displayArea(){}
} width = 2
length = 5
width = 4
width = 4 length = 3
length = 2
Syntax of defining an Instance/object of
a Class
ClassName objectName =new constructor ;

Rectangle r= new Rectangle();

•Every object has a unique identity, its own state


Access Specifiers
• Used to control access to members (attributes and methods) of the
class

Public : Members declared with public access specifier can be


accessed inside as well as outside of the class.
• Mostly, functions are kept public.

private: Members declared with private access specifier can only be


accessed inside the class.
• These members can be accessed by functions that are members of
the same class.

• Why to keep some members public?


• Because class cannot be accessed if all members
will be private.
Rule of Thumb:
Class Example Keep data attributes
private and functions public

class Rectangle To protect data from


{ unwanted access and
modification a.k.a data
private int width; hiding
Private Members
private int length;

public void displayWidth();


public void displayLength(); Public Members

public void displayArea();


}
More on Access Specifiers

• Can be listed in any order in a class

• Can appear multiple times in a class

• If not specified, the default is private


Class versus Structure

• A class is similar to struct, but not the same

• Members of a struct are public by default

struct Rectangle
Members of a class
{ are
double width; private by default

double length;
} r1;

cout << r1.width; //legal because width is public


Class versus Structure
• A class is similar to struct, but not the same
• Members of a class are private by default

class Rectangle
{
private double width;
private double length;
};
class main {

Public static void main() {


Rectangle r1 =new Rectangle(); //class object
System.out.println(r1.width); //ERROR, width is private
}
How to code Class

Access any public


members
of the class using the dot
operator:
r1.displayArea(
)
Data Hiding
• Information Hiding mean “Showing only those details to the outside
world which are necessary for the outside world and hiding all other
details from the outside world.”
• Real life example of information hiding: An email server may have
account information of millions of people but it will share only our
account information with us if we request it to send anyone else
accounts information our request will be refused.

Example of Data Hiding:

◾ Consider the same example of object Ali

◾ You can see that Ali stores his personal information in itself
and its behavior is also implemented in it.

◾ Now it is up to object Ali whether he wants to share that information with


outside world or not. Same thing stands for its behavior if some other
object in real life wants to use his behavior of walking it can not use it
without the permission of Ali.
ENCAPSULATION
•In programming, Restricting data members to be accessed from
within a class is called ―data hiding.
i.e. the data members declared as private is hidden from
outside the class. Data hiding is also known as
―encapsulation”.

◾Encapsulation means “we have enclosed all the characteristics


of an object in the object itself” Encapsulation and information
hiding are much related concepts (information hiding is achieved
using Encapsulation).

◾Encapsulation is combining both the data members and


member functions in one unit.
◾All information related to an object is stored within the object2
2
and it can only be manipulated by the object itself. Or it can be
manipulated if some part of it is kept public.
Defining a Member Functions-inside class
class Rectangle {
Private double width;
Private double length;

Public double calcArea() {


return width * length;}
}

public class Main {


public static void main(String[] args) {
}
}

Java doesn’t allow method definitions to exist outside the


class body (like C++ does).
Private Member Functions
It is used for internal processing by the
class Rectangle { class, not for use outside of the class
private double width;
private member function
private double length;
private double calcArea(double w, double l){
Width=w;
Length=l;
return length * width; }
public void displayArea()
{
System.out.Println(calcArea(10, 20));}
}
public class Main {
public static void main(String[] args) {
Rectangle obj = new Rectangle();
obj.displayArea(); }}
Setters and Getters

• Setter (Mutator): a member function that assigns a


value to a class data member

• Getter (Accessor): a function that reads/gets a value


from a class data member.
class Rectangle {
Private double width;
EXAMPLE
Private double length;

public void setWidth(double w){ //setter


width = w; }
public void setLength(double l){ //setter
length = l; }
Public double getWidth(){ //getter
return width; }
Public double getLength(){ //getter
return length; }
}
class Main {
public static void main(String[] args) {
Rectangle rect = new Rectangle();
rect.setWidth(5.0);
rect.setLength(10.0);
System.out.println("Width: " + rect.getWidth());
System.out.println("Length: " + rect.getLength()); } }
Code outside the class must use the class's
public member functions to interact with the
object

Constraints can be added in setters to prevent unwanted


values in data members
Pointers in JAVA, do not Exist
• Java does not have explicit pointers like C++ does.
However, in Java, all object variables are references,
which behave somewhat like pointers but with important
differences in terms of safety and abstraction.

• How Java Handles Object References:


In Java, when you create an object and assign it to a
variable, that variable holds a reference to the memory
location where the object is stored. This reference is
automatically managed by Java, so there is no need to
explicitly use pointers like in C++. You cannot perform
pointer arithmetic or directly manipulate memory.
EXAMPLE: BOX CLASS
class Box {
double width;
// No access specifier mentioned means
double height; that specifier here is: package-private
double depth;
}
class BoxDemo { // This class declares an object of type
public static void main(String Box.
args[]) { Box mybox = new
Box();
double vol;
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
vol = mybox.width
// compute volume of *box
mybox.height *
mybox.depth;
System.out.println("Volume is " + vol);
Volume is
} }
3000.0
// This program declares two Box mybox1.width = 10;
objects. mybox1.height = 20;
class Box mybox1.depth = 15;
{ /* assign different values to
double width; mybox2's instance variables */
double height; mybox2.width = 3;
double depth; mybox2.height = 6;
} mybox2.depth = 9;
class BoxDemo2 { // compute volume of first box
public static void main(String vol = mybox1.width * mybox1.height
args[]) { * mybox1.depth;
System.out.println("Volume is " +
Box mybox1 = new Box();
vol);
Box mybox2 = new Box(); // compute volume of second box
◾ This means that if we have two
double vol;
Box objects, each has its own vol = mybox2.width * mybox2.height
copy of the instance variables * mybox2.depth;
(depth, width, and height). System.out.println("Volume is " +
◾ It is important to understand vol);
that changes to the instance }
} Volume is
variables of one object have no
3000.0
effect on the instance variables
ASSIGNING OBJECT REFERENCE VARIABLES
◾ Object reference variables act differently when an
assignment takes place.
◾ Example:
◾ Box b1 = new Box();
◾ Box b2 = b1;

◾ Here, b1 and b2 will both refer to the same object.


◾ The assignment of b1 and b2 did not allocate any
memory or copy any part of the original object.
◾ It simply makes b2 refer to the same object as does
b1.
◾ Thus, any changes made to the object through b2 will
effect the object to which b1 is referring, since they
ASSIGNING OBJECT REFERENCE VARIABLES

width
b1 height
depth
Box
object

b2

When we assign one object reference variable to


another object reference variable, we are not
creating a copy of the object, we are only making a
copy of the reference.
• In Java, both rect1 and rect2 refer to the same
object, not separate objects. This is because when
you assign rect2 = rect1, you are not creating a
new object. Instead, rect2 becomes a reference to
the same object in memory that rect1 points to.
Both rect1 and rect2 are referencing the same
instance of the Rectangle class.
• In C++, Rectangle rect2 = rect1; creates a copy of
rect1. Changes made to rect2 do not affect rect1
because they are two different objects in memory.
• In Java, both rect1 and rect2 refer to the same object, not separate
objects. This is because when you assign rect2 = rect1, you are not
creating a new object. Instead, rect2 becomes a reference to the
same object in memory that rect1 points to. Both rect1 and rect2 are
referencing the same instance of the Rectangle class.
• In C++, Rectangle rect2 = rect1; creates a copy of rect1. Changes
made to rect2 do not affect rect1 because they are two different
objects in memory.
ACCESS SPECIFIERS/MODIFIERS IN JAVA
As the name suggests access specifiers in Java
helps to restrict the scope of a class, constructor
, variable , method or data member.
There are four types of access specifiers
available in java:

•Default – No keyword required


•Public
•Private
•Protected

When you don't set access specifier for the 3


4

element, it will follow the default accessibility


level. So, we can access class, method, or field
which belongs to same package, but not from
NOTE

• An object cannot access its private members, as shown in


(b).
• It is OK, however, if the object is declared in its own class,
as shown in (a).

4
0
EXAMPLES

• The private modifier restricts access to within a class,


• The default modifier restricts access to within a
package,
• The public modifier enables unrestricted access.
VISIBILITY MODIFIER OF CLASSES

• The default modifier on a class restricts


access to within a package
• The public modifier enables unrestricted
access.
3
9

You might also like