0% found this document useful (0 votes)
8 views245 pages

Object Oriented Programming Basics

This document provides an overview of Object Oriented Programming (OOP) methodology, covering its fundamentals, features, and differences from procedural programming. It outlines key concepts such as classes, objects, encapsulation, inheritance, and polymorphism, as well as specifics about Java programming, including its runtime environment and features. Additionally, it discusses the structure of Java programs and the process of compiling and executing Java code.

Uploaded by

m36278791
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views245 pages

Object Oriented Programming Basics

This document provides an overview of Object Oriented Programming (OOP) methodology, covering its fundamentals, features, and differences from procedural programming. It outlines key concepts such as classes, objects, encapsulation, inheritance, and polymorphism, as well as specifics about Java programming, including its runtime environment and features. Additionally, it discusses the structure of Java programs and the process of compiling and executing Java code.

Uploaded by

m36278791
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Object Oriented Programming Methodology

Module 1 : Fundamentals of Object Oriented Programming

Faculty In-charge:
Pragya Gupta
E-mail: pragya.g@[Link]

8/27/2020 1
Contents
• Procedural Programming Approach
• Structured Programming Approach
• Modular Programming Approach
• Object Oriented Programming Approach
• Objects and Classes
• OOP Features
• Static and Dynamic Binding
• Cohesion and Coupling

8/27/2020 2
Objective
• Understand what is Object Oriented programming
• Understand the principles of OOP
• How is OOP different from Procedural languages
• Problems in Procedural programming and how OOP overcomes them
• Know Java features and its Runtime Environment
• Understand basic structure of a Java program
• Know about the various constituents of JDK and its development environments

8/27/2020 3
Procedural Programming Approach
• Specifying the steps the program must take to reach the desired state
• Based upon the concept of the procedure call
• Procedures:
q Routines, subroutines, methods, or functions that contain a series of computational steps to be
carried out

• Any given procedure might be called at any point during a program's execution,
including by other procedures or itself
• Using a procedural language, the programmer specifies language statements to
perform a sequence of algorithmic steps

8/27/2020 4
Procedural Programming Approach
• Complexity increases as the length of a program increases .
• Divide a large program into different functions or modules
• Problems with Procedural languages
q functions have unrestricted access to global data
q that they provide poor mapping to real world
q Procedural languages are not extensible
• Example: Fortran, C, Pascal

8/27/2020 5
Structured Programming Approach

• A technique for organizing and coding programs in which hierarchy of modules is


used

• Each module has a single entry and single exit point


• Control is passed downward through the structure without unconditional branches
to higher levels

• Three types of control flow: Sequential, Test or Selection, Iteration

8/27/2020 6
Modular Programming Approach

• A technique for separating functionality into independent, interchangeable modules


• Each module contains everything necessary to execute only one aspect
• Sub-programs or functions

8/27/2020 7
Introduction to OOP
• A programming paradigm
• deals with concepts of object to build programs and software
applications
• Modeled around real world
• The world we live in is full of objects
• Every object has a well defined identity, attributes and behavior
• Objects exhibit the same behavior in programming.

8/27/2020 8
OOP Features
• Data Abstraction
• Encapsulation
• Inheritance
• Polymorphism

8/27/2020 9
OOP Approach
• Uses "objects"
• Data structures encapsulating data fields and procedures together with their
interactions – to design applications and computer programs.
• Object-oriented programming (OOP) involves programming using
objects
• An object represents an entity in the real world that can be distinctly
identified
• For example, a student, a desk, a circle, a button, and even a loan can all be
viewed as objects
• OOP features : Data abstraction, encapsulation, polymorphism, and
inheritance

8/27/2020 10
Comparison of OO and Procedural Languages
Procedural language Object Oriented language
Separate data from function that operate on them Encapsulate data and methods in a class

Not suitable for defining abstract types Suitable for defining abstract types

Debugging is difficult Debugging is easier

Difficult to implement change Easier to manage and implement change

Not suitable for larger applications/programs Suitable for larger programs and applications

Analysis and design not so easy Analysis and Design Made Easier

Faster Slower

Less flexible Highly flexible

Data and procedure based Object oriented

Less reusable More reusable

Only data and procedures are there Inheritance, encapsulation and polymorphism are key
features
Use top down approach Use bottom up approach

Only a function call to another Object communication is there

C, Basic, FORTRAN JAVA,C++, [Link], C#.NET

8/27/2020 11
Java Essentials

• A high level language

• Java Bytecode – intermediate code

• Java Virtual Machine (JVM) – interpreter for bytecode

8/27/2020 12
Java Translation

Java source
code Java
bytecode

Java
compiler
Java Bytecode
interpreter compiler

Machine
code

8/27/2020 13
Java Translation

• The Java compiler translates Java source code into a special representation called
bytecode
• Java bytecode is not the machine language for any traditional CPU
• Another software tool, called an interpreter translates bytecode into machine
language and executes it
• Therefore the Java compiler is not tied to any particular machine
• Java is considered to be architecture-neutral

8/27/2020 14
Java Runtime

Java Runtime Environment includes JVM, class libraries and other


supporting files

JAVA SOURCE CODE


Compilation

JAVA BYTE CODE


Interpretation

JAVA VIRTUAL MACHINE


(JVM)

8/27/2020 15
Java Approach

8/27/2020 16
Java Features
• Platform Independence
• Object oriented
• Compiled and interpreted
• Robust
• Security
• Strictly typed language
• Lack of pointers
• Garbage collection
• Strict compile time checking
• Sandbox security

8/27/2020 17
Java Features

• Multithreaded
• Dynamic binding
• Performance
• Networking
• No pointers
• No global variables
• Automatic Garbage collection

8/27/2020 18
Differences between C++ and Java

• Operator overloading
q Not supported in Java
q Exception is ‘+’
• Explicit boolean type
q Boolean is an explicit type, different from int
q Only two boolean literals are provided i.e. true and false
q These cannot be compared with integers 0 and 1 as used in some other
languages
• Array length accessible
q All array objects in java have a length variable associated with them to
determine the length of the array

8/27/2020 19
Differences between C++ and Java
• goto
q Instead of goto, break and continue are supported
• Pointers
q There are no pointers in Java
• null pointers reasonably caught
q Null pointers are caught by a NullPointerException
• Memory management
q Explicit destructor is not needed
q The use of garbage collection prevents memory leaks and referencing freed memory
• Automatic variable initialization
q Variables are automatically initialized except local variables
• Runtime container bounds checks
q The bounds of containers (arrays, strings, etc.) are checked at runtime and an
IndexOutOfBoundsException is thrown if necessary.

8/27/2020 20
Differences between C++ and Java

• All definitions are well defined


q Methods and fields carry explicitly one of the access modifiers
• Sizes of the integer types defined
q The sizes of the integer types byte, short, int and long are defined to be 1, 2, 4 and 8 bytes.
• Unicode provided
q Unicode represents character in most of the languages for e.g. Japanese, Latin etc
• String class
q An explicit predefined String class is provided along with StringBuffer and new StringBuilder
class

8/27/2020 21
Differences between C++ and Java

• Extended utility class libraries: package [Link]


q Supported among others: Enumeration (an Iterator interface), Hashtable, Vector
• Multithreading support with synchronization
q Java supports Multithreading with synchronization among them.
• Default access specifier added
q By default, in java all variables, methods and classes have default privileges which are
different from private access specifier
q Private is the default access specifier in C++

8/27/2020 22
JVM and JRE

JVM is a part of JRE

Java Runtime Environment

Operating Systems (Windows, Unix, etc.)

Hardware (Intel, Motorola, Alpha, etc.)

8/27/2020 23
Program Structure

• A Java Application
consists of a collection
of classes
• A class is a template
containing methods and
variables

8/27/2020 24
First Java Program

/* Call this file “[Link]”.*/


class Example {
//your program starts execution with a call to //main()
public static void main(String args[ ]){
[Link](“This is a simple Java program”);
}
}

8/27/2020 25
First Java Program

class Example {

public static void main (String args[])


{
[Link]("Welcome to OOPM 2022-23");
}
}

8/27/2020 26
Executing Java Programs
• Entering the source code: text editor like notepad or any IDE
• Saving the source code:
q Select File | Save As from the notepad menu
q In the ‘File name’ field, type “[Link]” within the double quotes
q In the ‘Save as type’ field select All Files (*.*).
q Click enter to save the file
• Compiling & running the source
q type cmd at the run prompt
q move to the folder that contains the saved [Link] file
q compile the program using javac
q C:\javaeg\>javac [Link]

8/27/2020 27
Executing Java Programs
• Compilation creates a file called [Link]
• This class contains bytecode which is interpreted by JVM.
• To execute the program type the following command at the dos
prompt:
q C:\javaeg\>java Example
• The output of the program is shown below:
q This is a simple Java program

8/27/2020 28
Why save as [Link]?

• The name of the .class file will match exactly with the name of the
source file
• That is why it is a good idea to give the Java source files the same
name as that of the class they contain
• Java is case-sensitive
• So example and Example are two different class names

8/27/2020 29
Installation of Java

• Download the JDK installer


• Run the JDK installer.
• Update PATH Environment variables.
• Test the installation – run javac and java on command prompt

8/27/2020 30
Installed Directory structure

8/27/2020 31
Installed Directory Structure

• [Link] file contains all the core class binaries, and is used by JDK in this form
• include\ directory contains a set of C and C++ header files for interacting with
C and C++
• lib\ directory contains non-core classes like [Link] and [Link] used by tools
and utilities in JDK
• bin\ The bin directory contains the binary executables for Java
q For example, Java Compiler (Java), Java Interpreter (Java)
• jre\ is the root directory for the Java runtime environment
• db\ contains java database

8/27/2020 32
Tools in JDK

Basic Tools in Java

8/27/2020 33
IDE
• Tools specifically designed for writing Java code.
• Tools offer a GUI environment to compile and debug your Java
program easily from the editor environment, as well as browse
through your classes etc.
• Popular IDE’s
q Eclipse
q Netbeans
q Kawa
q JCreator

8/27/2020 34
Objects and Classes
• The state of an object (also known as its properties or attributes) is
represented by data fields with their current values
• Example:
q A circle object has a data field radius, which characterizes a circle
q A rectangle object has the data fields width and height, which characterize a
rectangle
• The behavior of an object (also known as its actions) is defined by methods
• To invoke a method on an object is to ask the object to perform an action
• Example:
q getArea() and getPerimeter() maybe defined
q getArea() maybe invoked by circle object to return its area and getPerimeter() to
return its perimeter

8/27/2020 35
Objects and Classes
• Objects of the same type are defined using a common class
• A class is a template, blueprint, or contract that defines what an
object’s data fields and methods will be
• An object is an instance of a class, many instances can be created
• Creating an instance is referred to as instantiation.
• The terms object and instance are often interchangeable

8/27/2020 36
Objects
Class Name: Circle A class template

Data Fields:
radius is _______

Methods:
getArea

Circle Object 1 Circle Object 2 Circle Object 3 Three objects of


the Circle class
Data Fields: Data Fields: Data Fields:
radius is 10 radius is 25 radius is 125

• An object has both a state and behavior


• The state defines the object, and the behavior defines what the object does

8/27/2020 37 37
Classes

• Classes are constructs that define objects of the same type


• A Java class uses variables to define data fields and methods to define behaviors
• Additionally, a class provides a special type of methods, known as constructors
• Constructors are invoked to construct objects from the class

8/27/2020 38 38
Classes
class Circle {
/** The radius of this circle */
double radius = 1.0; Data field

/** Construct a circle object */


Circle() {
}
Constructors
/** Construct a circle object */
Circle(double newRadius) {
radius = newRadius;
}

/** Return the area of this circle */


double getArea() { Method
return radius * radius * 3.14159;
}
}

8/27/2020 39 39
OOP Concepts
• Key OOP Concepts
– Object, Class
– Data Abstraction
– Encapsulation
– Inheritance and Subclasses
– Polymorphism
q Run-time polymorphism
q Compile-time polymorphism

8/27/2020 40
Object

• Defined as instance of a class


• Example: table, chair are all instances of the class Furniture.
• Objects have unique identity, state and behavior
• State is defined by the attributes of the object.
• Different objects have different attributes ( characteristics)
• Example: the attributes of student are name, roll number etc
• Behavior actually determines the way an object interacts with other objects.
• Synonym to functions

8/27/2020 41
Object

• Definition: a thing that has identity, state, and behavior


– identity: a distinguished instance of a class
– state: collection of values for its variables
– behavior: capability to execute methods

– variables and methods are defined in a class

8/27/2020 42
Class

• Blueprint for an object, a plan, or template


• Description of a number of similar objects is also called class
• A class is also defined as a new data type; a user defined type
• Defining a class doesn’t create an object
• Classes are logical in nature.
• Example: Furniture does not have any existence but tables and chairs
do exist

8/27/2020 43
Class

• Definition: a collection of data (fields/ variables) and methods that


operate on that data

– define the contents/capabilities of the instances (objects) of the


class
– a class can be viewed as a factory for objects
– a class defines a recipe for its objects

8/27/2020 44
Instantiation

• Object creation
• Memory is allocated for the object’s fields as defined in the class
• Initialization is specified through a constructor
– a special method invoked when objects are created

8/27/2020 45
Abstraction

• OOP is about abstraction


• In real life, Humans manage complexity by abstracting details away
• In programming, we manage complexity
q by concentrating only on the essential characteristics and
q suppressing implementation details
• Encapsulation and Inheritance are examples of abstraction
q What does the verb “abstract” mean?

8/27/2020 46
Encapsulation

• A key OO concept: “Information Hiding”


• Key points
– The user of an object should have access only to those methods
(or data) that are essential
– Unnecessary implementation details should be hidden from the
user
– Binding of data and procedure
– In Java/C++, use classes and access modifiers (public, private,
protected)

8/27/2020 47
Encapsulation

8/27/2020 48
Inheritance

• Inheritance:
– programming language feature that allows for the implicit
definition of variables/methods for a class through an existing
class
• Subclass relationship
– B is a subclass of A
– B inherits all definitions (variables/methods) in A

8/27/2020 49
Reuse

• Inheritance encourages software reuse


• Existing code need not be rewritten
• Successful reuse occurs only through careful planning and design
– when defining classes, anticipate future modifications and
extensions

8/27/2020 50
Polymorphism

• “Many forms”
– allow several definitions under a single method name
• Example:
– “move” means something for a person object but means
something else for a car object
• Dynamic binding:
– capability of an implementation to distinguish between the
different forms during run-time

8/27/2020 51
Static and Dynamic Binding

• Association of method call to the method body is known as binding


• There are two types of binding:
o Static Binding that happens at compile time
o Dynamic Binding that happens at runtime

8/27/2020 52
Static and Dynamic Binding

• If you have more than one method of same name (method overriding) or two variable of same name in
same class hierarchy it gets tricky to find out which one is used during runtime as a result of there
reference in code.

• This problem is resolved using static and dynamic binding in Java.

• Binding is the process used to link which method or variable to be called as result of the reference in
code.
o Most of the references is resolved during compile time but some references which depends upon Object
and polymorphism in Java is resolved during runtime when actual object is available.

o When a method call is resolved at compile time, it is known as static binding, while if method invocation is
resolved at runtime, it is known as Dynamic binding or Late binding.

53 8/27/2020
Lecture12 53
Static and Dynamic Binding
• private, final and static methods and variables uses static binding and resolved by compiler because
compiler knows that they can't be overridden and only possible methods are those, which are defined
inside a class, whose reference variable is used to call this method.

• Static binding uses Type information for binding while Dynamic binding uses Object to resolve binding.

• Static Binding
o Variables – static binding
Variables are resolved using static binding which makes there execution fast because no time is wasted to find
correct method during runtime.
o Private, final, static methods – static binding

o Overloaded methods are resolved using static binding

• Dynamic Binding
o Overridden methods are resolved using dynamic binding at runtime.

54 8/27/2020
Lecture12 54
Coupling

Coupling refers to the extent to


which a class knows about the
other class.
There are two types of coupling
− Tight Coupling(a bad
programming design)
− Loose Coupling(a good
programming design)

8/27/2020 55
Tight Coupling
If a class A has some public data members and another class B is accessing these data
members directly using the dot operator (which is possible because data members were
declared public), the two classes are said to be tightly coupled

Let's say, the same class A has a String data member, name, which is declared public and this
class also has getter and setter methods that have implemented some checks to make sure -
• A valid access of the data member, name i.e. it is only accessed when its value is not null,
and
• A valid setting of the data member, name i.e. it cannot be set to a null value

But these checks implemented in the methods of class A to ensure a valid access and valid
setting of its data member, name, are bypassed by its direct access by class B, due to tight
coupling between two classes.

8/27/2020 56
Tight Coupling
Program Analysis
• Class A has an instance variable, name, which is declared public
• Class A has two public getter and setter methods which check for a valid access and valid
setting of data member - name
• Class B creates an object of class A and directly sets the value of its data member, name,
to null and directly accesses its value because it was declared public
• Thus, the validity checks for the data member, name, which were implemented
within getName() and setName() methods of class A are bypassed, which shows that
class A is tightly coupled to class B, and it is a bad design

8/27/2020 57
Loose Coupling
• A good application designing is creating an application with loosely coupled classes by
following encapsulation
• i.e. by declaring data members of a class with the private access modifier, which disallows
other classes to directly access these data members, and forcing them to call
the public getter, setter methods to access these private data members

8/27/2020 58
Loose Coupling
Program Analysis
• Class A has an instance variable, name, which is declared private
• Class A has two public getter and setter methods which check for a valid access and valid
setting of the data member, name
• Class B creates an object of class A, calls the getName() and setName() methods and
their implemented checks are properly executed before the value of instance
member, name, is accessed or set
• It shows that class A is loosely coupled to class B, which is a good programming design

8/27/2020 59
Cohesion

• Cohesion refers to the extent to which


a class is defined to do a specific
specialized task
• A class created with high cohesion is
targeted towards a single specific
purpose, rather than performing many
different purposes

• There are two types of cohesion


− Low cohesion(a bad programming
design)
− High Cohesion(a good
programming design)

8/27/2020 60
Low Cohesion
• When a class is designed to do many different tasks rather than focus on a single specialized
task, this class is said to be a "low cohesive" class
• Low cohesive classes are said to be badly designed, as it requires a lot of work at creating,
maintaining and updating them
Program
Example of a low cohesion class
class PlayerDatabase
{ public void connectDatabase();
public void printAllPlayersInfo();
public void printSinglePlayerInfo();
public void printRankings();
public void printEvents();
public void closeDatabase(); }

8/27/2020 61
Low Cohesion
Program Analysis
• Here, we have a class PlayerDatabase which is performing many different tasks like
connecting to a database, printing the information of all the players, printing information of a
single player, printing all the events, printing all the rankings and finally closing all opened
database connections
Now, such a class is not easy to create, maintain and update, as it is involved in performing
many different tasks i.e. a programming design to avoid

8/27/2020 62
High Cohesion
• A good application design Program
//Example of high cohesion classes
is creating an application
class PlayerDatabase {
with high cohesive classes, ConnectDatabase connectD= new connectDatabase();
which are targeted towards PrintAllPlayersInfo allPlayer= new PrintAllPlayersInfo();

a specific specialized PrintRankings rankings = new PrintRankings();


CloseDatabase closeD= new CloseDatabase();
task and such classes are
PrintSinglePlayerInfo singlePlayer = PrintSinglePlayerInfo(); }
not only easy to create but class ConnectDatabase { //connecting to database. }
also easy to maintain and class CloseDatabase { //closing the database connection. }

update class PrintRankings { //printing the players current rankings. }


class PrintAllPlayersInfo { //printing all the players information. } class
PrintSinglePlayerInfo { //printing a single player information. }

8/27/2020 63
High Cohesion
Program Analysis
• Here we have created several different classes, where each class is performing a specific
specialized task, which leads to an easy creation, maintenance and modification of these classes
• Classes created by following this programming design are said to performing a cohesive role
and are termed as high cohesion classes, which is an appropriate programming design to follow
while creating an application

8/27/2020 64
Thank You

8/27/2020 65
Object Oriented Programming Methodology

Module 2 : Class, Object, Method and Constructor

Faculty In-charge:
Pragya Gupta
E-mail: pragya.g@[Link]

8/27/2020 1
Contents

• Class
• Objects
• Methods
• Constructors

8/27/2020 2
Parts of a class

• The class contains two different sections:


− Variable declarations: Describe state
− Method declaration: Describe behavior
classDeclaration {
memberVariableDeclarations
methodDeclarations
}

8/27/2020 3
Example
Class SalesTaxCalculator for calculating and displaying the tax

class SalesTaxCalculator {
float amount=100.0f;
float taxRate=10.2f;
void calculateTax() {
float taxAmt = amount*taxRate/100;
[Link](taxAmt);
}
}

8/27/2020 4
Why should we use classes and objects?

Modularity and
information hiding i.e. data
encapsulation can be
incorporated using an
object, in software.
Classes, being blueprints,
provide the benefit of
reusability.

8/27/2020 5
Creating Objects

• Java object is created with a statement like this one:


SalesTaxCalculator obj1 = new SalesTaxCalculator ( );

• This statement creates a new SalesTaxCalculator object


• This single statement declares, instantiates, and
initializes the object

8/27/2020 6
Declaring an Object
• Object declaration is same as variable declaration
− for e.g. SalesTaxCalculator obj1;
• Generally the declaration is as follows:
type name;
− Where type is the type of the object (i.e. class name)
− name is the name of the reference variable used to refer the object
• Difference between variables and objects:
− A variable holds a single type of literal
− An object is an instance of a class with a set of instance variables and methods which
performs certain tasks depending on what methods have been defined for

8/27/2020 7
Initializing an object
• By initializing an object we mean that the instances variables are
assigned some values
• This task is accomplished using a constructor.
• The final object creation can be said as complete when the objects
are initialized, either with an implicit constructor or an explicit
constructor
• This object creation can be used in programming code:
− SalesTaxCalculator obj1 = new SalesTaxCalculator ( );
• Here all the three operations, object declaration, object instantiation
and object initialization are done by one statement only

8/27/2020 8
Initializing an object
The above process actually takes place in following way:

8/27/2020 9
Instance Variable
• A class can have many instances, each instance having its own set of variables
E.g.
class SalesTaxCalculator {
float amount=100.0f; // instance variable
float taxRate=10.2f; //instance variable
void calculateTax() {
float taxAmt = amount*taxRate/100;
[Link](taxAmt); }
public static void main (String args[ ]) {
SalesTaxCalculator obj1 = new SalesTaxCalculator();
SalesTaxCalculator obj2 = new SalesTaxCalculator();
[Link]("Amount in Object 1: "+ [Link]);
[Link]("Tax Rate in Object 1: "+ [Link]);
[Link]("Amount in Object 2: "+ [Link]);
[Link]("Tax Rate in Object 2: "+ [Link]);
}}
8/27/2020 10
Accessing Instance Variables
• For accessing value of an object
− [Link]
• To assign values to the variables of an object
− [Link] = value
• There are three ways of assigning values to the instance variables in
the objects:
− Assigning values directly to the instance variables as shown below,
float amount=100.0f;
− Assigning values through a setter method
− Values can be assigned using constructors

8/27/2020 11
Instance variable (contd.)
• Each variable declared inside a class and outside the methods
• Except static variables, because they are created whenever an
instance (object) of the class is created
• These variables are initialized by the constructors
• In the above example the two objects obj1 and obj2 will have their
own set of instance variables.
• i.e. obj1 will have its own amount and taxRate whereas obj2 will
have its own set of amount and taxRate

8/27/2020 12
Methods

• Similar to a function in any other programming languages.


• None of the methods can be declared outside the class.
• Why use methods?
− To make code reusable
− To parameterize code
− For top-down programming
− To simplify code

8/27/2020 13
Method (contd.)

• General syntax for a method declaration:


[modifiers] return_type method_name (parameter_list) [throws_clause] {
[statement_list]}
• The method declaration includes:
− Modifiers: The modifiers are optional. They can be, public, protected, default
or private, static, abstract, final, synchronized, throws

8/27/2020 14
Method (contd.)
• Return Type:
− can be either void or if a value is returned, it can be either a primitive
type or a class
− If the method declares a return type, then before it exits it must have a
return statement
• Method Name:
− The method name must be a valid Java identifier
• Parameter List:
− Contains zero or more type/identifier pairs make up the parameter list
− Each parameter in parameter list is separated by a comma
• Curly Braces:
− The method body is contained in a set of curly braces (opening ‘{‘ and
closing ‘}’)
8/27/2020 15
Method Example
class Circle {
float pi = 3.14f;
float radius;
void setRadius(float rad) {
radius = rad;}
float calculateArea() {
float area = pi* radius*radius;
return (area);
} }

8/27/2020 16
Method invocation
• Methods cannot run on their own, they need to be invoked by the
objects they are a part of
• When an object calls a method, it can pass on certain values to the
methods (if methods accept them)
• The methods can also return values from themselves if they wish to
• Data that are passed to a method are known as arguments or
parameters

8/27/2020 17
Method Invocation
Function Definition
• Formal Parameters: The identifier used in a method to stand for the value that is
passed into the method by a caller
• Actual Parameters: The actual value that is passed into the method by a caller
Function Call

• The number and type of the actual and formal parameters should be same for a
method
• In Java, all values are passed by value. This is unlike some other programming
languages that allow pointers to memory addresses to be passed into methods

8/27/2020 18
Method Invocation

class CallMethod {
public static void main (String args[]) {
float area1;
Circle circleobj = new Circle();
[Link](3.0f);
area1 = [Link]();
[Link]("Area of Circle = " + area1);
}}

8/27/2020 19
Constructors
• Java has a mechanism, known as constructor, for automatically initializing the
values for an object, as soon as the object is created
• Constructors have the same name as the class it resides in and is syntactically
similar to a method
• It is automatically called immediately after the object for the class is created by
new operator
• Constructors have no return type, not even void, as the implicit return type of a
class’ constructor is the class type itself
• Types of Constructors: Implicit/Default, Explicit, Parameterized

8/27/2020 20
Constructors
Circle() {
} Constructors are a special kind of
Circle(double newRadius) {
radius = newRadius;
methods that are invoked to construct
}
objects.

8/27/2020 21
Constructors, cont.

A constructor with no parameters is referred to as a no-arg


constructor
− Constructors must have the same name as the class itself
− Constructors do not have a return type—not even void
− Constructors are invoked using the new operator when an object is created
− Constructors play the role of initializing objects

8/27/2020 22
Creating Objects Using Constructors

new ClassName();
Example:

new Circle();

new Circle(5.0);

8/27/2020 23
Default Constructor

• A class may be defined without constructors


• A no-arg constructor with empty body is implicitly defined in
the class
• This constructor, called a default constructor
– is provided automatically only if no constructors are explicitly
defined in the class

8/27/2020 24
Static keyword

• Different objects, variables and methods will occupy different areas of


memory when created/called
• Sometimes we would like to have multiple objects, share variables or
methods
• The static keyword effectively does this for us
• Static keyword can be applied to variables/methods and blocks of code.
• Java supports three types of variables: Local, Instance and Class
variables
– Local variables are declared inside a method, constructor, or a block of code
– Instance variable are declared inside a class, but outside a method

8/27/2020 25
Static keyword

• Class/static variables declaration is preceded with a static keyword. They are


also declared inside a class, but outside a method
• The most important point about static variables is that there exists only one a
single copy of static variables per class
− The effect of doing this is that when we create multiple objects of that class, every object
shares the static variable i.e. there is only one copy of the variable declared as static. We can
declare a variables as static as under:
static int var = 0;

8/27/2020 26
Instance Variables vs. Class Variables

• All instances of the class share the static variables of the class
• A class variable can be accessed directly with the class name,
without the need to create an instance
• Without the static keyword, it's called “instance variable”, and
each instance of the class has its own copy of the variable

8/27/2020 27
Static Methods
• Like static variables, we do not need to create an object to call our
static method
• Simply using the class name will suffice
• Static methods however can only access static variables directly
• Variables that have not been declared static cannot be accessed by the
static method directly
• i.e. the reason why we create an object of the class within the main
(which is static) method to access the instance variables and call
instance methods
• To make a method static, we simply precede the method declaration
with the static keyword

8/27/2020 28
Static Methods
static void aMethod(int param1) {
.....
.....
}
• When we declare a method static, we are basically saying that there
should only be one instance of this method within our program (e.g, as
in the main method)
• Methods can also be declared with the static keyword
– static int computeArea(int length, int width) { }

8/27/2020 29
Static initialization block
• A block of statements with static keyword applied to it.
• used for initializing static or class variables.
• in case some logic is used for assigning values to the variables, static
blocks can be used.
• The syntax for static block is as follows:
static{
...
}

8/27/2020 30
Static initialization block
• The static executes as soon as the class loads even before the JVM
executes the main method
• There can be any number of static blocks within the class and they will
be executed in the order in which they have appeared in the source
code

8/27/2020 31
Instance initialization block
• In case the static keyword is dropped from this block, it becomes an
instance initialization block
• Actually the code of instance initialization block is placed in the <init>
method, which is created for every constructor by the compiler, before
the source code mentioned by programmer in the constructor

8/27/2020 32
Automatic Garbage Collection
• The Garbage Collector (GC) collects and removes unreferenced objects
from the heap area
• It is the process of reclaiming the runtime unused memory
automatically by destroying them
• Garbage collection makes Java memory efficient because it removes
the unreferenced objects from heap memory and makes free space for
new objects
• It involves two phases:
• Mark - in this step, the GC identifies the unused objects in memory
• Sweep - in this step, the GC removes the objects identified during the
previous phase

8/27/2020 33
Unreferenced Objects

8/27/2020 34
Unreferenced Objects
• By nulling a reference
Employee e=new Employee();
e=null;
• By assigning a reference to another
Employee e1=new Employee();
Employee e2=new Employee();
e1=e2;//now the first object referred by e1 is available for garbage collection

• By anonymous object
new Employee();

8/27/2020 35
Object Oriented Programming Methodology

Module 3 : Arrays, Strings and Vectors

Faculty In-charge:
Pragya Gupta
E-mail: pragya.g@[Link]

8/27/2020 1
Contents

• Arrays

8/27/2020 2
Arrays
• Array is a memory space allocated, which can store multiple values of same data type, in
contiguous locations
• This memory space, which can be perceived to have many logical contiguous locations, can be
accessed with a common name
• A specific element in an array is accessed by the use of a subscript or index used in brackets, along
with the name of the array
− For example, marks[5] would mean marks of 5th student
• While the complete set of values is called an array, the individual values are known as elements
• Arrays can be two types:
− one dimensional array
− multi-dimensional array

8/27/2020 3
1-D Arrays
• In one-dimensional array, a single subscript or index is used, where each index value refers to
individual array element
• The indexation will start from 0 and will go up to n-1, i.e. the first value of the array will have an
index of 0 and the last value will have an index of n–1, where ŋ is the number of elements in the
array
• So, if an array named marks has been declared to store the marks of 5 students, the computer
reserves five contiguous locations in the memory, as shown below

8/27/2020 4
1-D Arrays

8/27/2020 5
Creation of Arrays

• Creating an array, similar to an object creation, can inherently


involve three steps:
− Declaring an array
− Creating memory locations
− Initializing/assigning values to an array

8/27/2020 6
Declaring an Array

• Declaring an array is same as declaring a normal variable except


that you must use a set of square brackets with the variable type
• There can be two ways in which an array can be declared:
− type arrayname[ ];
− type[ ] arrayname;
• For e.g.
− int marks[ ]; or
− int[ ] marks;

8/27/2020 7
Creating memory locations
• An array is more complex than a normal variable, so we have to assign memory
to the array when we declare it
• You assign memory to an array by specifying its size
• Interestingly, our same old new operator helps in doing the job, just as shown
below:
− Arrayname = new type [size];

• So, allocating space and size for the array named as marks can be done as,
− marks = new int[5];

8/27/2020 8
Initializing/assigning values to an array
• Assignment of values to an array, which can also be termed as
initialization of array, can be done as follows,
− Arrayname[index] = value;

• The creation of list of marks to be assigned in array, named as


marks has already been shown in the section above

8/27/2020 9
Setting values in an array
public class Array {
public static void main(String[] args) {
int[] marks = new int[5];
marks[0] = 60;
marks[1] = 58;
marks[2] = 50;
marks[3] = 78;
marks[4] = 89;
} }
Alternatively you can also use:
int marks[] = {60, 58, 50, 78, 89}

8/27/2020 10
Using for-each with Arrays
• The format of for-each is as follows:
− for (type var : arr){
− // Body of loop
− }
• For example, to calculate the sum of the elements of the array, for-each can be
used as follows.
− int[] arr= {2,3,4,5,6};
− int sum = 0;
− for( int a : arr)
− // a gets successively each value in arr
− {
− sum += a;
− }
• The disadvantage of for-each approach is that it is possible to iterate in forward
direction only by single steps

8/27/2020 11
Multidimensional Arrays/ Jagged Arrays

8/27/2020 12
Collection Framework
• Provides an architecture to store and manipulate a group of objects
• Achieve all the operations that you perform on a data such as
searching, sorting, insertion, manipulation, and deletion
• Java Collection means a single unit of objects
• Java Collection framework provides many interfaces (Set, List,
Queue, Deque) and classes (ArrayList, Vector, LinkedList,
PriorityQueue, HashSet, LinkedHashSet, TreeSet)

8/27/2020 13
8/27/2020 14
Iterator interface

• Iterator interface provides the facility of iterating the elements in forward


direction only

8/27/2020 15
Collection Interface

• Interface which is implemented by all the classes in the collection


framework
• It declares the methods that every collection will have
• Collection interface builds the foundation on which the collection
framework depends
• Some of the methods of Collection interface are
o Boolean add ( Object obj)
o Boolean addAll ( Collection c)
o void clear(), etc.
which are implemented by all the subclasses of Collection interface

8/27/2020 16
List Interface

• List interface is the child interface of Collection interface


• It inhibits a list type data structure in which we can store the ordered collection of objects
• It can have duplicate values
• List interface is implemented by the classes ArrayList, LinkedList, Vector, and Stack.
• To instantiate the List interface, we must use :
List <data-type> list1= new ArrayList();
List <data-type> list2 = new LinkedList();
List <data-type> list3 = new Vector();
List <data-type> list4 = new Stack();

8/27/2020 17
ArrayList
• Java ArrayList class uses a dynamic array for storing the elements( there is no size
limit)
• We can add or remove elements anytime, much more flexible than the traditional array
• It is found in the [Link] package
• The ArrayList in Java can have the duplicate elements also
• It implements the List interface so we can use all the methods of List interface here.
• The ArrayList maintains the insertion order internally

8/27/2020 18
LinkedList
• Java LinkedList class uses a doubly linked list to store the elements
• It provides a linked-list data structure

8/27/2020 19
ArrayList v/s LinkedList

8/27/2020 20
21

Vectors
• Vector implements a dynamic array of objects
• Vector proves to be very useful if you don't know the size of the
array in advance or you just need one that can change sizes over
the lifetime of a program
• Vector can contain heterogeneous objects
• We cannot store elements of primitive data type; first it need to
be converted to objects. A vector can store any objects
• Its defined in [Link] package and class member of the Java
Collections Framework

8/27/2020 21
Vectors

• Vector implements List Interface


• A vector has an initial capacity, if this capacity is reached then size of
vector automatically increases
• This default initial capacity of vectors are 10
• Each vector tries to optimize storage management by maintaining a
capacity and a capacityIncrement arguments
• To traverse elements of a vector class we use Enumeration interface

8/27/2020 22
Vector Methods

8/27/2020 23
Vector Methods

8/27/2020 24
Vector Methods

8/27/2020 25
Access Protection

• Four Access specifier in Java

8/27/2020 26
Access Specifiers

• public means accessibility for all


• private means accessibility from within the class only
• default (blank) access specifiers are accessible only from within the
package
• protected means accessibility outside the packages but only to subclasses

8/27/2020 27
Access Specifiers

8/27/2020 28
Access Protection

• method abc() is accessible from A, B as well as C, but neither from D


nor E
• protected method are accessible outside the package also, but only to
subclasses outside the package. For example, the method xyz()
accessible from classes A, B, C, D, but not from E
• public method pqr() is accessible from all classes A, B, C, D and E

8/27/2020 29
toString() Method

• If you want to represent any object as a string, toString()


method comes into existence
• The toString() method returns the String representation of the object
• By overriding the toString() method of the Object class, we can return
values of the object, so we don't need to write much code

8/27/2020 30
Java Wrapper Classes
• For each primitive type, there is a corresponding wrapper class
designed
• Are wrapper around primitive data types
• Allow for situations where primitives cannot be used but their
corresponding objects are required
• Normally Used to convert a numeric value to a String or vice-versa
• Just like String, Wrapper objects are also immutable
• All the wrapper classes except Character and Float have two
constructors—one that takes the primitive value and another that takes
the String representation of the value
• Character has one constructor and float has three

8/27/2020 31
Java Wrapper Classes

8/27/2020 32
Java Wrapper Classes
• For each primitive type, there is a corresponding wrapper class
designed
• Are wrapper around primitive data types
• Allow for situations where primitives cannot be used but their
corresponding objects are required
• Normally Used to convert a numeric value to a String or vice-versa
• Just like String, Wrapper objects are also immutable
• All the wrapper classes except Character and Float have two
constructors—one that takes the primitive value and another that takes
the String representation of the value
• Character has one constructor and float has three

8/27/2020 33
Java Wrapper Classes
• They convert primitive data types into objects. Objects are needed if
we wish to modify the arguments passed into a method (because
primitive types are passed by value).
• The classes in [Link] package handles only objects and hence
wrapper classes help in this case also.
• Data structures in the Collection framework, such
as ArrayList and Vector, store only objects (reference types) and not
primitive types.
• An object is needed to support synchronization in multithreading

8/27/2020 34
Java Wrapper Classes

• Converts primitive to wrapper


o double a = 4.3;
o Double wrp = new Double(a);
• Each wrapper provides a method to return the primitive value.
o double r = [Link]();

8/27/2020 35
Autoboxing and Unboxing
• Autoboxing: Automatic conversion of primitive types to the object of
their corresponding wrapper classes is known as autoboxing
• Unboxing: It Automatically converting an object of a wrapper class to
its corresponding primitive type is known as unboxing

8/27/2020 36
String Class

• Are basically immutable objects in Java


• Immutable means once created the, strings cannot be changed
• Whenever we create strings, it is this class that is instantiated
• In Java strings can be instantiated in two ways:
o String x= “String Literal Object”;
o String y=new String (“String object is created here”);

8/27/2020 37
String Example

String a=”Hello”; String b=”Hello”;


String c=new String(“Hello”);
String d=new String(“Hello”);
String e=new String(“Hello, how are you?”);
if(a==b)
[Link](“object is same and is being shared by a & b”);
else
[Link](“Different objects”);
if(a==c)
[Link](“object is same and is being shared by a & c”);
else
[Link](“Different objects”);

8/27/2020 38
String Example

if(c==d)
[Link](“same object”);
else
[Link](“Different objects”);
String f=[Link]();
if(f==a)
[Link](“Interned object f refer to the already created object a
in the pool”);
else
[Link](“Interned object does not refer to the already created
objects, as literal was not present in the pool. It is a new object which has
been created in the pool”);

8/27/2020 39
String Example

8/27/2020 40
String Manipulation

• Strings in Java are immutable (read only) in nature, Once defined cannot
be changed.
• Let us take an example:
o String x = “Hello”; // ok
o String x = x +”World”; // ok, but how?
• the ‘+’ operator concatenates If at least one of the operand is a string.
• The second statement gets converted to the following statement
automatically
o String x=new StringBuffer(). append(x). append(“World”). toString();

8/27/2020 41
Common Methods of String Class

8/27/2020 42
Common Methods of String Class

8/27/2020 43
StringBuffer Class
• StringBuffer class is used for representing changing strings
• StringBuffer offers more performance enhancement whenever we change
Strings, because it is this class that is actually used behind the curtain
• Just like any other buffer, StringBuffer also has a capacity and if the
capacity is exceeded, then it is automatically made larger
• The initial capacity of StringBuffer can be known by using a method
capacity()

8/27/2020 44
Methods of StringBuffer Class

8/27/2020 45
StringBuilder Class
• A substitute of StringBuffer class.
• This class is faster than StringBuffer class, as it is not synchronized
• append(), insert(), delete(), deleteCharAt(), replace(), and reverse() return
StringBuilder objects rather than StringBuffer objects
• The line creates a StringBuilder object
o StringBuilder s=new StringBuilder();
o construct a StringBuilder object with an initial capacity of 16 characters. Similar to that
of StringBuffer

8/27/2020 46
Object Oriented Programming Methodology

Module 4 : Inheritance and Interface

Faculty In-charge:
Pragya Gupta
E-mail: pragya.g@[Link]

8/27/2020 1
Contents

• Inheritance

8/27/2020 2
Inheritance
• Is the ability to derive something specific from something
generic
• aids in the reuse of code
• A class can inherit the features of another class and add its own
modification
• The parent class is the super class and the child class is known
as the subclass
• A subclass inherits all the properties and methods of the super
class

8/27/2020 3
Inheritance

8/27/2020 4
Types of Inheritance

• Single
• Multiple
• Multilevel
• Hierarchical
• Hybrid

8/27/2020 5
Single Level Inheritance
• Classes have only one base class

8/27/2020 6
Multi Level Inheritance
• There is no limit to this chain of inheritance (as shown below)
but getting down deeper to four or five levels makes code
excessively complex

8/27/2020 7
Multiple Inheritance
• A class can inherit from more than one unrelated class

8/27/2020 8
Hierarchical Inheritance
• In hierarchical inheritance, more than one class can inherit from
a single class. Class C inherits from both A and B

8/27/2020 9
Hybrid Inheritance
• is any combination of the above defined inheritances

8/27/2020 10
Deriving Classes
• Classes are inherited from other class by declaring them as a part of its
definition
• For e.g.
o class MySubClass extends MySuperClass
• extends keyword declares that MySubClass inherits the parent class
MySuperClass

8/27/2020 11
Inheritance

8/27/2020 12
Method Overriding

• A method in a subclass has the same name and type signature as a


method in its superclass, then the method in the subclass is said to
override the method in the superclass
• It is a feature that supports polymorphism
• When an overridden method is called through the subclass object, it will
always refer to the version of the method defined by the subclass
• The superclass version of the method is hidden

8/27/2020 13
Late Binding Vs Early Binding

• Binding is connecting a method call to a method body


• When binding is performed before the program is executed, it is called
early binding
• If binding is delayed till runtime it is late binding
• also known as dynamic binding or runtime binding
• All the methods in Java use late binding (except static and final)

8/27/2020 14
super keyword

• For invoking the methods of the super class


• For accessing the member variables of the super class
• For invoking the constructors of the super class

8/27/2020 15
Problem and Solution

• Two methods being called by two different objects (inherited), instead the
job can be done by one object only, i.e. using super keyword

8/27/2020 16
Final keyword

• Declaring constants (used with variable and argument declaration)


o final int MAX=100;

• Disallowing method overriding (used with method declaration)


o final void show (final int x)

• Disallowing inheritance (used with class declaration).


o final class Demo {}

8/27/2020 17
Abstract class

• Abstract classes are classes with a generic concept, not related to a


specific class
• Abstract classes define partial behaviour and leave the rest for the
subclasses to provide
• contain one or more abstract methods
• abstract method contains no implementation, i.e. no body
• Abstract classes cannot be instantiated, but they can have reference
variable
• If the subclasses does not override the abstract methods of the abstract
class, then it is mandatory for the subclasses to tag itself as abstract

8/27/2020 18
Why create abstract methods?

• to force same name and signature pattern in all the subclasses


• subclasses should not use their own naming patterns
• They should have the flexibility to code these methods with their own
specific requirements

8/27/2020 19
Shadowing Vs Overriding

• Shadowing of fields
o occurs when variable names are same
o It may occur when local variables and instance variable names collide within a
class or variable names in superclass and subclass are same
• In case of methods,
o instance methods are overridden whereas static methods are shadowed
o The difference between the two is important because shadowed methods are
bound early whereas instance methods are dynamically (late) bound.

8/27/2020 20
Interfaces

• Interface is a collection of methods which are public and abstract by


default
• The implementing objects have to inherit the interface and provide
implementation for all these methods
• multiple inheritance in Java is allowed through interfaces
• Interfaces are declared with help of a keyword interface

8/27/2020 21
Syntax for Creating Interface

interface interfacename
{
returntype methodname(argumentlist);

}
The class can inherit interfaces using implements keyword
o class classname implements interfacename{}

8/27/2020 22
Variables in Interface

• They are implicitly public, final, and static


• As they are final, they need to be assigned a value compulsorily
• Being static, they can be accessed directly with the help of an interface
name
• as they are public we can access them from anywhere

8/27/2020 23
Extending Interfaces

• One interface can inherit another interface using the extends keyword and
not the implements keyword
• For example,
interface A extends B { }

8/27/2020 24
Interface Vs Abstract Class

8/27/2020 25
Similarities between Interface and Abstract Class

• Both cannot be instantiated, i.e. objects cannot be created for both of


them
• Both can have reference variables referring to their implementing classes
objects
• Interfaces can be extended, i.e. one interface can inherit another interface,
similar to that of abstract classes (using extends keyword)
• static / final methods can neither be created in an interface nor can they
be used with abstract methods

8/27/2020 26
Object Oriented Programming Methodology

Module 5: Class Diagram

Faculty In-charge:
Pragya Gupta
E-mail: pragya.g@[Link]

8/27/2020 1
Contents

• Class Diagram

8/27/2020 2
What is a Class Diagram?
• Suppose you have to design a system. Before implementing a
bunch of classes, you’ll want to have a conceptual understanding of
the system
−What classes do I need?
−What functionality and information will these classes have?
−How do they interact with one another?
−Who can see these classes?
• That’s where class diagrams come in
• Class diagrams are a neat way of visualizing the classes in your
system before you actually start coding them up
• They’re a static representation of your system structure

8/27/2020 3
Class Representation in UML
− A class is represented as a box with 3 compartments.
• The uppermost one contains the class name
• The middle one contains the class attributes
• The last one contains the class methods

ClassName

attributes

operations

8/27/2020 4
Class Names

ClassName • The name of the class is the only required tag in the
graphical representation of a class
attributes
• It always appears in the top-most compartment

operations

8/27/2020 5
Class attributes

ClassName • An attribute is a named property of a Person


class that describes the object being name : String
attributes
modeled address : Address
birthdate : Date
operations • In the class diagram, attributes appear ssn : Id
in the second compartment just below
the name-compartment

8/27/2020 6
Class attributes (Contd.)

Attributes are usually listed in the form:


ClassName Person
attributeName : Type

attributes • A derived attribute is one that can be


name : String
computed from other attributes, but doesn’t address : Address
actually exist. birthdate : Date
operations • For example, a Person’s age can be computed ssn : Id
from his birth date
• A derived attribute is designated by a
preceding ‘/’ as in:

/ age : Date

8/27/2020 7
Class attributes (Contd.)

ClassName Attributes can be: Person


+ public
attributes # protected + name : String
- private # address : Address
# birthdate : Date
operations / derived / age : Date
- ssn : Id

8/27/2020 8
Class Operations

Person • Operations describe the class behavior and


appear in the third compartment
name : String • You can specify an operation by stating its
address : Address signature: listing the name, type, and default
birthdate : Date
ssn : Id
value of all parameters, and, in the case of
functions, a return type
eat
sleep PhoneBook
work
play
newEntry (n : Name, a : Address, p : PhoneNumber, d : Description)
getPhone ( n : Name, a : Address) : PhoneNumber

8/27/2020 9
Depicting Classes
When drawing a class, you needn’t show attributes and operation in every diagram

Person Person Person

name : String
birthdate : Date
Person ssn : Id

name Person eat()


address sleep()
birthdate work()
eat
play()
play

8/27/2020 10
Relationships

• In UML, object interconnections (logical or physical), are modeled as relationships

• There are three kinds of relationships in UML:

• dependencies

• generalizations

• associations

8/27/2020 11
Relationships

8/27/2020 12
Dependency Relationships

• A dependency indicates a semantic relationship between two or more elements


• The dependency from CourseSchedule to Course exists because Course is used in both the add and
remove operations of CourseSchedule

CourseSchedule

Course

add(c : Course)
remove(c : Course)

8/27/2020 13
Generalization Relationships

Person

• A generalization connects a subclass to its superclass


• It denotes an inheritance of attributes and behavior from the
superclass to the subclass and indicates a specialization in the
subclass of the more general superclass

Student

8/27/2020 14
Generalization Relationships (Contd.)

UML permits a class to inherit from multiple superclasses, although some programming languages (e.g.,
Java) do not permit multiple inheritance

Student Employee

TeachingAssistant

8/27/2020 15
Inheritance
− Indicates that child (subclass) is considered to be a specialized form of the parent (super class).
− For example consider the following:

8/27/2020 16
Association
− An association is a relationship between two separate classes
− It joins two entirely separate entities.
− There are four different types of association:
• Bi-directional
• Uni-directional
• Aggregation (includes composition aggregation)
• Reflexive
− Bi-directional and uni-directional associations are the most common ones
− This can be specified using multiplicity (one to one, one to many, many to many, etc.)
− A typical implementation in Java is through the use of an instance field
− The relationship can be bi-directional with each class holding a reference to the other
− Associations that have the same class at both ends are known as reflexive associations

8/27/2020 17
Association Relationships

• If two classes in a model need to communicate with each other, there must be link between them
• An association denotes that link

Student Instructor

8/27/2020 18
Association Relationships (Contd.)

We can indicate the multiplicity of an association by adding multiplicity adornments to the line denoting the
association

The example indicates that a Student has one or more Instructors:

Student Instructor
1..*

8/27/2020 19
Multiplicity

• After specifying the type of association relationship by connecting the classes, you can also declare the
cardinality between the associated entities
• For example:
• The below UML diagram shows that a house has exactly one kitchen, exactly one bath, at least one
bedroom (can have many), exactly one mailbox, and at most one mortgage (zero or one)

8/27/2020 20
Multiplicity

8/27/2020 21
Association Relationships (Contd.)

The example indicates that every Instructor has one or more Students:

Student Instructor
1..*

8/27/2020 22
Association Relationships (Contd.)

We can also indicate the behavior of an object in an association (i.e., the role of an object) using
rolename

teaches learns from


Student Instructor
1..* 1..*

8/27/2020 23
Association Relationships (Contd.)

We can also name the association.

membership
Student Team
1..* 1..*

8/27/2020 24
Association Relationships (Contd.)

We can specify dual associations

member of

1..* 1..*
Student Team

1 president of 1..*

8/27/2020 25
Association Relationships (Contd.)
• We can constrain the association relationship by defining the navigability of the association
• Here, a Router object requests services from a DNS object by sending messages to (invoking the operations of)
the server
• The direction of the association indicates that the server has no knowledge of the Router

Router DomainNameServer

8/27/2020 26
Association Relationships (Contd.)

Associations can also be objects themselves, called link classes or an association classes

Registration

modelNumber
serialNumber
warrantyCode

Product Warranty

8/27/2020 27
Association Relationships (Contd.)

A class can have a self association

next

LinkedListNode
previous

8/27/2020 28
Association Relationships (Contd.)
• We can model objects that contain other objects by way of special associations called aggregations and
compositions
• An aggregation specifies a whole-part relationship between an aggregate (a whole) and a constituent part,
where the part can exist independently from the aggregate
• Aggregations are denoted by a hollow-diamond adornment on the association

Engine

Car
Transmission

8/27/2020 29
Dependency - Aggregation

• A special form of association which is a unidirectional (a.k.a one way) relationship


between classes
• The best way to understand this relationship is to call it a “has a” or “is part of”
relationship
• For example, consider the two classes: Wallet and Money
• A wallet “has” money, but money doesn’t necessarily need to have a wallet so it’s a
one directional relationship

8/27/2020 30
Association Relationships (Contd.)
• A composition indicates a strong ownership and coincident lifetime of parts by the whole (i.e.,
they live and die as a whole)
• Compositions are denoted by a filled-diamond adornment on the association

Scrollbar
1 1

Window Titlebar
1 1

Menu
1 1 .. *

8/27/2020 31
Composition
• A restricted form of Aggregation in which two entities (or you can say classes) are
highly dependent on each other
• A human needs a heart to live and a heart needs a human body to function on
• In other words when the classes (entities) are dependent on each other and their life
span are same (if one dies then another one does too) then it’s a composition

8/27/2020 32
Interfaces

• An interface is a named set of operations that specifies the


behavior of objects without showing their inner structure
<<interface>> • It can be rendered in the model by a one- or two-
ControlPanel compartment rectangle, with the stereotype <<interface>>
above the interface name

8/27/2020 33
Interface

A relationship between two model elements, in which one model element implements/executes the
behavior that the other model element specifies

8/27/2020 34
Object Oriented Programming Methodology

Module 6 : Exception Handling, Packages, Multithreading

Faculty In-charge:
Pragya Gupta
E-mail: pragya.g@[Link]

8/27/2020 1
Contents

• Exception Handling
• Packages

8/27/2020 2
Exception

• Exceptions in real life are rare


• are usually used to denote something unusual that does not conform to
the standard rules
• In programming, exceptions are events that arise due to the occurrence of
unexpected behaviour in certain statements, disrupting the normal
execution of a program

8/27/2020 3
Causes of Exception

• Exceptions can arise due to a number of situations. For example,


o Trying to access the 11th element of an array when the array contains of only 10
element (ArrayIndexOutOfBoundsException)
o Division by zero (ArithmeticException)
o Accessing a file which is not present (FileNotFoundException)
o Failure of I/O operations (IOException)
o Illegal usage of null. (NullPointerException)

8/27/2020 4
Exception classes

• Top class in exception hierarchy is Throwable


• This class has two siblings: Error and Exception
• All the classes representing exceptional conditions are subclasses of the
Exception class

8/27/2020 5
What happens when an execution occurs?
• runtime environment identifies the type of Exception and throws the
object of it
• If the method does not employ any exception handling mechanism
– the exception is passed to the caller method, and so on
• If no exception handling mechanism is employed in any of the Call Stack
methods
– the runtime environment passes the exception object to the default exception
handler available with itself
– The default handler prints the name of the exception along with an explanatory
message followed by stack trace at the time the exception was thrown and the
program is terminated

8/27/2020 6
Stack Trace

8/27/2020 7
Types of Exceptions

8/27/2020 8
Exception Hierarchy

8/27/2020 9
Exception Handling Techniques

• try..catch
• throw
• throws
• finally

8/27/2020 10
Packages

• Collection of classes and interfaces


• Provides a unique namespace for the classes
• Declaration resides at the top of a Java source file
• A package can contain the following.
o Classes
o Interfaces
o Enumerated types
o Annotations

8/27/2020 11
Packages (Contd.)
• Class that reside inside a package cannot be referred by their own name
alone
• The package name has to precede the name of the class of which it is a
part of
• All classes are part of some or the other package
• If the package keyword is not used in any class for mentioning the name
of the package, then it becomes part of the default/unnamed package

8/27/2020 12
Access Protection
• Four access specifiers in Java

8/27/2020 13
Access Specifiers

• Public: Accessibility for all


• Private: Accessibility from within the class only
• Default (blank): Accessible only from within the package
• Protected: Accessibility outside the packages but only to subclasses

8/27/2020 14
Access Protection

8/27/2020 15
Thread Life Cycle
• In Java, a thread always exists in any one of the following states
• These states are:
• New
• Active
• Blocked / Waiting
• Timed Waiting
• Terminated

8/27/2020 16
Thread States

• New
o Whenever a new thread is created, it is always in the new state.
o For a thread in the new state, the code has not been run yet and thus has not begun
its execution

• Active
o When a thread invokes the start() method, it moves from the new state to the
active state
o The active state contains two states within it: one is runnable, and the other
is running
8/27/2020 . 17
Thread States(Contd.)
• Runnable:
− A thread, that is ready to run is then moved to the runnable state
− In the runnable state, the thread may be running or may be ready to run at any given instant of time
− It is the duty of the thread scheduler to provide the thread time to run, i.e., moving the thread the
running state
− A program implementing multithreading acquires a fixed slice of time to each individual thread
− Each and every thread runs for a short span of time and when that allocated time slice is over, the thread
voluntarily gives up the CPU to the other thread, so that the other threads can also run for their slice of
time
− Whenever such a scenario occurs, all those threads that are willing to run, waiting for their turn to run,
lie in the runnable state
− In the runnable state, there is a queue where the threads lie

18
8/27/2020
.
Thread States(Contd.)

• Running
o When the thread gets the CPU, it moves from the runnable to the
running state
o Generally, the most common change in the state of a thread is from
runnable to running and again back to runnable

8/27/2020 19
Thread States(Contd.)
• Blocked or Waiting
o Whenever a thread is inactive for a span of time (not permanently) then, either the thread is in the
blocked state or is in the waiting state
o For example, a thread (let's say its name is A) may want to print some data from the printer.
However, at the same time, the other thread (let's say its name is B) is using the printer to print
some data. Therefore, thread A has to wait for thread B to use the printer. Thus, thread A is in the
blocked state. A thread in the blocked state is unable to perform any execution and thus never
consume any cycle of the Central Processing Unit (CPU). Hence, we can say that thread A
remains idle until the thread scheduler reactivates thread A, which is in the waiting or blocked
state

8/27/2020 20
Thread States(Contd.)
• Timed Waiting
o Sometimes, waiting for leads to starvation
o For example, a thread (A) has entered the critical section of a code and is not willing to leave that
critical section. In such a scenario, another thread (B) has to wait forever, which leads to
starvation. To avoid such scenario, a timed waiting state is given to thread B. Thus, thread lies in
the waiting state for a specific span of time, and not forever. A real example of timed waiting is
when we invoke the sleep() method on a specific thread. The sleep() method puts the thread in the
timed wait state. After the time runs out, the thread wakes up and start its execution from when it
has left earlier.

8/27/2020 21
Thread States(Contd.)
• Terminated
o A thread reaches the termination state because of the following reasons:
− When a thread has finished its job, then it exists or terminates normally.
− Abnormal termination: It occurs when some unusual events such as an unhandled
exception or segmentation fault
o A terminated thread means the thread is no more in the system. In other words,
the thread is dead, and there is no way one can respawn (active after kill) the dead
thread

8/27/2020 22
Life Cycle of a Thread

8/27/2020 23
Multithreading

• A thread is a single sequential flow of control within a program


• Multitasking
o Process Based
o Thread Based

8/27/2020 24
Process Vs Thread

• If we assume programs as processes, then process based multitasking is nothing


but execution of more than one program concurrently
• While the thread based multitasking is executing a program having more than
one thread, performing different tasks simultaneously
• Processes are heavyweight tasks
• Threads are light weight tasks

8/27/2020 25
Thread based Multitasking: Multithreading

• Multithreading enables programs to have more than one execution paths


(separate) which execute concurrently
• Each such path of execution is a thread
• Through multithreading, efficient utilization of system resources can be
achieved, such as maximum utilization of CPU cycles and minimizing idle time
of CPU

8/27/2020 26
Thread class
• In Java, there is a class named as Thread class, which belongs to [Link]
package, declared as,
• public class Thread extends Object implements Runnable
• This class encapsulates any thread of execution. Threads are created as the
instance of this class, which contains run() methods in it. The functionality of
the thread can only be achieved by overriding this run() method.
• public void run( ) {
// statement for implementing thread
}

8/27/2020 27
Methods
• run() should be invoked by an object of the concerned
thread
• This can be achieved by creating the thread and
calling start() on that

8/27/2020 28
Thread class Constructors

• Thread( )
• Thread(String threadName)
• Thread(ThreadGroup threadGroup, String threadName)

8/27/2020 29
Main Thread

• Every Java program has a default thread, main thread


• When the execution of Java program starts, the JVM creates
the main thread and calls the program's main() method
within that thread
• Apart from this JVM also creates some invisible threads,
which are important for JVM housekeeping tasks
• Programmers can always take control of the main thread
8/27/2020 30
Main Thread (contd.)

• thread object can be created by using the currentThread()


method, which returns a reference to the current thread
• The main thread can be controlled by this reference only

8/27/2020 31
Thread creation
• By extending the Thread class
• By implementing the Runnable interface
Extending the Thread class
Steps to be undertaken for Thread creation
• Declare your own class as extending the Thread class
• Override the run( ) method, which constitutes the body of the thread
• Create the thread object and use the start( ) method to initiate the
thread execution
8/27/2020 32
Declaring a class

Any new class can be declared to extend the Thread class, thus
inheriting all the functionalities of the Thread class.

class NewThread extends Thread


{
…………………………..
…………………………..
}
Here, we have a new type of thread, named as ‘NewThread’

8/27/2020 33
Overriding the run( )method
• The run() method has been inherited by the class NewThread.
• The run() method has to be overridden by writing code required for
the thread. The thread behaves as per this code segment.
public void run( )
{
//code segment providing the functionality of thread
}

8/27/2020 34
Starting New Thread
• Third part talks about start() method, required to create and initiate an instance
of our thread class
• Following piece of code is responsible for the same
NewThread thread1 = new NewThread( );
[Link]( );

• First line creates an instance of class NewThread, where the object is just
created. The thread is in newborn state
• Second line, which calls the start() method moves the thread in runnable state,
where the java runtime will schedule the thread to run by invoking the run()
method automatically
8/27/2020 35
Implementing the Runnable interface
• Runnable interface is implemented by Thread class in the package [Link]
• This interface is declared as,
• public interface Runnable
• The interface needs to be implemented by any class whose instance is to be executed by a
thread
• The implementing class must also override a void method named as run(), defined as a lone
method in the Runnable interface as
public void run( )
{
…………………
}
8/27/2020 36
Runnable interface (contd.)

• The object's run() method is called automatically whenever the


thread is scheduled for execution by the thread scheduler
• The functionality of the thread depends on the code written within
this run() method
• Other methods can be called from within run()
• The Thread will stop as soon as the run() exits

8/27/2020 37
Runnable interface (contd.)

• Once a class that implements Runnable interface is created, an object


of Thread class must be instantiated from within that class
• The constructors of Thread class helps in instantiating the object of
Thread class
• Thread(Runnable threadObj)
• Thread(Runnable threadObj, String threadName)
• Thread(ThreadGroup threadGroup, Runnable threadObj)
• Thread(ThreadGroup threadGroup, Runnable threadObj, String threadName)

8/27/2020 38
Runnable interface (contd.)

• Even if thread is created, it will not start executing unless the start()
method of the Thread class is called
• This start() method when called, in turn calls the run()

8/27/2020 39

You might also like