You are on page 1of 58

TEMPLATE 4: The Lesson Structure 

(Will be used individually during the self-paced write shop)


Module No. Module 1: Basic OOP Concepts
and Title 
Lesson No. Lesson 1: Programming Paradigms
and Title 
Learning Describe the different programming paradigms commonly used in the industry.
Outcomes  
Time 0.5 hour 
Frame 
Introduction This lesson will discuss different programming paradigms and the advantages
of the Object-Oriented approach to software development and modeling. The
concepts of abstraction, encapsulation, inheritance, and polymorphism will be
explained.

Activity Think of an object you possess.

Analysis
1. Describe the current state and list two or three things you can do
with that object.
______________________________________________________
______________________________________________________
______________________________________________________
______________________________________________________

Abstraction  What is Object-Oriented Programming?

Just as new computing technologies are changing our world, so


too are new techniques and ideas changing the way we develop
computer systems. In the 1950s, the use of machine code
languages was common.

In the 1960s, high-level languages, which made programming simpler, became


common. However, these led to the development of large complex programs
that were difficult to manage and maintain.

In the 1970s, the structured programming paradigm became the accepted


standard for large complex computer programs. The structured programming
paradigm proposed methods to logically structure the programs developed into
separate smaller, more manageable components.

In the 1980s, ‘modular’ languages were developed that became the precursor to
modern Object-Oriented languages.

In the 1900s, the Object-oriented paradigm and component-based software


development ideas were developed, and Object-Oriented languages became the
norm from 2000 onwards.

The object-oriented paradigm is based on many of the ideas developed over the
previous 30 years of abstraction, encapsulation, generalization, and
polymorphism. It led to the development of software components where the
operation of the software and the data it operates on are modeled together.

Object-oriented programming involves the creation of objects that model a


business problem you are trying to solve (e.g., a bank account, a bank customer,
and a bank manager – could all be objects in a computerized banking system).
With each object you model, that data associated with it (i.e., it’s status at any
point in time) and the behavior associated with it (what our computer program
should allow that object to do).

In creating an object-oriented program, you define the properties of a class of


objects and then create individual objects from this class.

The Object-Oriented Paradigm

While you can focus your attention on the actual program code you are writing,
whatever development methodology is adopted, it is not the creation of the code
that is generally the source of most problems.

Most problems arise from:


● poor analysis and design: the computer system you create doesn’t do the
right thing.
● Poor maintainability: the system is hard to understand and revise when,
as inevitable, change requests arise.
The Object-Oriented programming paradigm aims to help overcome these
problems by assisting with the analysis and design tasks during the initial
software development phase and by ensuring that software is robust and
maintainable.

Object-Oriented Principles

Abstraction and encapsulation are fundamental principles that underline the


Object-Oriented approach to software development. Abstraction allows you to
consider complex ideas while ignoring irrelevant detail that would confuse you.
Encapsulation allows you to focus on what something does without considering
the complexities of how it works.

Two other fundamental principles of Object Orientation are


Generalization/specialization (which allows you to make use of Inheritance)
and Polymorphism.

Generalization/specialization allows you to define the general characteristics


and operations of an object and create more specialized versions of it. The
specialized versions of this object will automatically inherit all of the
characteristics of the more generalized object.

The final principle underlying Object Orientation is Polymorphism, which is the


ability to interact with an object as its generalized category regardless of its
more specialized category.

The Benefits of the Object-Oriented Programming Approach

Whether or not you develop programs in an object-oriented way before you


write the software, you must first create a model of what that software must be
able to do and how it should work. Object-oriented modeling is based on the
ideas of abstraction, encapsulation, inheritance, and polymorphism.

The general proponents of the object-oriented approach claim that this model
provides:
● better abstractions (modeling information and behavior together)
● better maintainability (more comprehensible, less fragile)
● better reusability (classes as encapsulated components)

Application  Discuss the validity of the following statement:

The object-oriented programming approach is ideal


for simulating real-world problems.

Well done! You have just finished Lesson 1 of this module. Should there be
Closure  some parts of the lesson you need clarification, feel free to ask your teacher?

Module No. Module 1: Basic OOP Concepts


and Title 
Lesson No. Lesson 2: Procedural Programming vs. OOP
and Title 
Learning Differentiate OOP from Procedural Programming
Outcomes  
Time 0.5 hour 
Frame 
Introduction
This lesson will discuss the difference between Object-Oriented Programming
from Procedural Programming. Also, it will tackle the object-oriented
programming concepts and their applicability for modeling and representing
real-world entities and their interactions in the problem-solving process.

Activity Consider the figure below showing procedural and object-oriented


programming.

Analysis 1. Based on the figure above, how does object-oriented programming


differ from the traditional procedural programming approach?
______________________________________________________
______________________________________________________
______________________________________________________

Abstraction  Object-Oriented Programming

The procedural approach to programming was the de facto approach in the early
days of programming. Here, code is modularized based on a system’s
processes.
For instance, in developing a library application system, we would have
considered processes such as checking in and out of books, making reservations
of books, cataloging books, and so on. Problem-solving would involve the
analysis of these processes in terms of the procedural tasks carried out and the
production of a system whose representation is based on the procedural flow of
the processes.

Object-oriented programming, on the other hand, models objects and their


interactions in the problem space and the production of a system based on these
objects and their interactions.

Since objects and their interactions characterize the real-world problem domain,
a software application developed using the object-oriented programming
approach will result in the production of a computer system that has a closer
representation of the real-world problem domain than would be the case if the
procedural programming approach is used.

Objects and Their Interactions in the Real World

Let us consider a real-world situation. There are two persons, Benjamin and his
wife, Bambie. They are customers of HomeCare, a company dealing with
luxurious furniture. HomeCare sells a variety of sofa sets. Each sofa set is
labeled with an identification number and a price tag. After viewing the sofa
sets for an hour, Benjamin and Bambie decide to purchase a green leather 5-
seater set. They approach Sean, a salesperson, to place their order.

In making his request known to Sean, Benjamin sends a message to Sean, “I


would like to purchase this green leather, 5-seater set. Can you please have it
sent to me by next Wednesday?”

The message that Benjamin has sent to Sean is a takeOrder message. It contains
information such as the type of sofa set (a green leather, 5-seater set) and the
date of delivery (next Wednesday). This information is known as the
parameters of
the takeOrder message.

In response to Benjamin’s message, Sean replies to Benjamin by returning the


result of his request. We can represent the interaction between Benjamin and
Sean graphically using Figure 1.
Figure 1.1: Interaction between Benjamin and Sean.

Sean was able to respond to Benjamin’s takeOrder message because he


understood it and had the means to handle Benjamin’s request. Although Sean
knew how to satisfy Benjamin’s request, Benjamin did not. Most of the time,
customers do not know how a salesperson has satisfied their orders. All they get
from salespersons are replies such as, “I am sorry, madam, we are unable to
satisfy your request because the sofa you wanted has been sold,” or “Sir, your
request has been satisfied. We will deliver the goods on Wednesday between 10
am to 11 am to the address indicated. Thank you for your order.”

Sean, as a salesperson at HomeCare, has a responsibility towards Benjamin. He


maintains his responsibility by applying a set of operations:

1. He determines if there is sufficient stock to satisfy Benjamin’s request.


2. He determines if the requested date for delivery is suitable.
3. He instructs the warehouse staff to deliver the goods to Benjamin’s address
on the required date if the above conditions are satisfied.
4. Finally, he informs Benjamin of the result of his request.

The interactions between Benjamin and Sean in the above real-world situation
can be represented in object-oriented programming terms. For instance,
Benjamin and Sean are objects that interact by sending messages. Benjamin is
thus a message-sending object, while Sean is a message-receiving object.
Alternatively, we can label Benjamin as a sender and Sean as a receiver.

The takeOrder request from Benjamin to Sean is an example of a message. It


may have additional, accompanying information known as parameters (or
arguments) of the message. The fact that Sean responded to Benjamin’s
message indicates that the message is valid. Each valid message corresponds to
a method that Sean uses to fulfill his responsibility to Benjamin.

On the other hand, an invalid message is one that the receiver cannot respond
to; that is, the receiver does not have a corresponding
method to match the message. For example, if Benjamin had requested a
discount on the price, his request would have been rejected because Sean, being
a salesperson, would not have the capability (or a corresponding method) to
respond to the message.

A method contains a number of operations detailing how Sean is to satisfy the


demand Benjamin put on Sean through the request.
Figure 1.2: Object interactions in object-oriented programming terms

While Benjamin may know what Sean can do through his methods, he may not
know how Sean does them. This is an important principle of object-oriented
programming known as information hiding: the sender of a message does not
know how a receiver will satisfy the request in the message.

Based on the above example, it is clear that maybe object-oriented


programming concepts such as an object, message, and method provide a close
representation of real-world objects and their interactions. These concepts are
thus suitable for simulating actual object interactions in real-world situations.

Application  Consider the following scenarios and outline the objects and their interactions
in terms of messages and arguments:
a) a driver driving a car;
b) a customer making a cash withdrawal from an automated teller
c) machine (ATM);
d) a customer buying a compact disk player from a vendor;
e) a traffic policeman directing traffic at a junction;
f) a lecturer delivering his/her lecture to a class of students;
g) (f) a tutorial discussion between an instructor and students.
Well done! You have just finished Lesson 2 of this module. Should there be
Closure  some parts of the lesson which you need clarification, feel free to ask your
teacher?

Module No. Module 1: Basic OOP Concepts


and Title 
Lesson No. Lesson 3: Fundamentals of Object-Oriented Programming Languages
and Title 
Learning Understand the basic programming syntax, structure, and constructs of different
Outcomes   OOP Languages.
Time 1 hour 
Frame 
Introduction This lesson will discuss the basic programming syntax, structure, and constructs
of different OOP Languages.

Activity Consider the people who work in a hospital.

1. List three common occupations of people you would expect to be


Analysis employed here. Now for each of these common occupations, list two
or three specific categories of staff.
___________________________________________________
___________________________________________________
___________________________________________________
___________________________________________________
___________________________________________________
___________________________________________________

Abstraction  Object-oriented Programming Language

Object-oriented programming language (OOPL) is a high-level programming


language based on the object-oriented programming (OOP) model.

OOPL incorporates logical classes, objects, methods, relationships, and other


processes with software and application design. The first OOPL was Simula, a
simulation creation tool developed in 1960.

Unlike conventional procedural languages, the programming syntax of an


object-oriented programming language is based on one or more objects,
whereas procedural language incorporates logical procedures. In OOPL, objects
interact with each other; they have their methods, procedures, and functions;
they are part of a class and may be reused in one or more programs. An OOPL
must exhibit native object-oriented functions, including data abstraction,
inheritance, encapsulation, class creation, and associated objects.

Most modern programming languages are object-oriented or support the OOP


model to an extent. Popular OOPLs include Java, C++, Python, and SmallTalk.

Example OOP Structure

Let’s take a real-world problem, and conceptually design an OOP software


program. Imagine running a pet sitting camp with hundreds of pets, and you
have to keep track of the names, ages, and days attended for each pet. How
would you design simple, reusable software to model the pets?

With hundreds of pets, if code had to be created from scratch for each new pet,
there would be way too much code. Here’s a code of creating two dog objects:

//Object of one individual dog


var rufus = {
name: "Rufus",
birthday: "2/1/2017",
age: function() {
return Date.now() - this.birthday;
},
attendance: 0
}

//Object of second individual dog


var fluffy = {
name: "Fluffy",
birthday: "1/12/2019",
age: function() {
return Date.now() - this.birthday;
},
attendance: 0
}

What do you notice about the code? There is a lot of duplicated code between
both objects - the age() function appears in each object. If you think about
hundreds of pets, you wouldn’t want to repeat it often. In OOP, programmers
think about how to model things using objects, so code is reusable and
maintainable.

Grouping related information together to form a class structure makes the code
shorter and easier to maintain.

In the pet sitting camp example, here’s how a programmer could think about
organizing an OOP:

1. Group pets into categories Like Dog, Cat


● Determine the information the software should model for each pet
category
2. Create classes
● Classes a blueprint of information for each pet
3. Add Attributes to classes
● Data fields to store for each pet, like name
4. Add Behaviors to classes
● Functionality that each pet needs to do, like bark
5. Create objects from the class
● Objects are individual instances of the class template
● In our case dogs like Rufus & Fluffy

The diagram below represents how to design an OOP: grouping the related data
and behaviors to form a simple template. In this case, the Dog class is a
simplified representation of everything we want to store in the software about
dogs. The Dog class is a generic template - containing only the structure about
information and behaviors common to all dogs. To create an individual dog, the
programmer instantiates an instance of the Dog Class and passes in information
from the individual dog.

Let’s say we wanted to store more information specific to French Bulldogs, we


can use the Dog class as a parent class, and add a child class French Bulldog
with more behaviors and data. Objects are created or instantiated from classes.
Rufus is an instance of the dog class. Fluffy & Maisel are instances of the
French Bulldog class. Inheritance is the ability to create parent and child
classes: the French Bulldog class inherits the Dog class. Inheritance is one of
the principles of OOP, as discussed in the previous lesson.

Figure 1.3 Sample OOP Design

Here’s a brief example:


The dog is a parent class with generic methods, a blueprint for creating any type
of dog. French Bulldog is a child class of the Dog parent class. The French
Bulldog class adds more specific attributes and methods unique to French
Bulldogs – like a nap. The French Bulldog class also inherits the attributes and
methods of the parent class. Next, the programmer creates instances of the
French Bulldog class – one named Fluffy and Maisel. Fluffy & Maisel can both
bark and nap. However, Rufus is an instance of the generic dog parent class so
that Rufus can bark, but he can’t nap. Nap is a method of the child class, and
Rufus is an object created from the parent class Dog.

Classes

In a nutshell, they’re essentially user-defined data types. Classes are where the
programmer creates a blueprint for the structure of methods and attributes.
Individual objects are instantiated, or created from this blueprint. Classes
contain fields for attributes and methods for behaviors. In our dog class
example, attributes include name & birthday, while methods include bark() and
updateAttendance().

Here’s a code snippet demonstrating how to program a dog class:

class Dog {
constructor(name, birthday) {
this.name = name;
this.birthday = birthday;
}

//Declare private variables


_attendance = 0;

getAge() {
//Getter
return this.calcAge();
}

calcAge() {
//calculate age using today's date and birthday
return Date.now() - this.birthday;
}

bark() {
return console.log("Woof!");
}

updateAttendance() {
//add a day to the dog's attendance days at the petsitters
this._attendance++;
}
}
Remember, the class is a template for modeling a dog, and an object is
instantiated from the class representing a single real-world thing - Rufus, the
dog.

Objects
Of course, OOP includes objects! Objects are instances of classes created with
specific data. For example, in the code snippet below, Rufus is an instance of
the dog class.

class Dog {
constructor(name, birthday) {
this.name = name;
this.birthday = birthday;
}

//Declare private variables


_attendance = 0;

getAge() {
//Getter
return this.calcAge();
}

calcAge() {
//calculate age using today's date and birthday
return Date.now() - this.birthday;
}

bark() {
return console.log("Woof!");
}

updateAttendance() {
//add a day to the dog's attendance days at the petsitters
this._attendance++;
}
}

//instantiate a new object of the Dog class, and individual dog named Rufus
const rufus = new Dog("Rufus", "2/1/2017");

When the new class Dog is called:


● A new object is created named Rufus
● The constructor runs name & birthday arguments and assigns values.

Attributes

Attributes are the information that is stored. Attributes are defined in the Class
template. When objects are instantiated, individual objects contain data stored
in the Attributes field.

The state of an object is defined by the data in the object’s attributes fields. For
example, a puppy and a dog might be treated differently at a pet camp. The
birthday could define the state of an object, and allow the software to handle
dogs of different ages differently.
Methods

Methods represent behaviors. Methods perform actions; methods might return


information about an object, or update an object’s data. The method’s code is
defined in the class definition. When individual objects are instantiated, these
objects can call the methods defined in the class. In the code snippet below, the
bark method is defined in Dog class, and the bark method is called on the Rufus
object.

class Dog {
//Declare protected (private) fields
_attendance = 0;

constructor(name, birthday) {
this.namee = name;
this.birthday = birthday;
}

getAge() {
//Getter
return this.calcAge();
}

calcAge() {
//calculate age using today's date and birthday
return this.calcAge();
}

bark() {
return console.log("Woof!");
}

updateAttendance() {
//add a day to the dog's attendance days at the petsitters
this._attendance++;
}
}

Methods often modify, update, or delete data. Methods don’t have to update
data through – for example, the bark method doesn’t update any data because
barking doesn’t modify any of the dog class’s attributes - name or birthday. The
updateAttendance() method adds a day the Dog attended the pet sitting camp.
The attendance attribute is important to keep track of for billing Owners at the
end of the month.

Methods are how programmers promote reusability and keep functionality


encapsulated inside an object. This reusability is a great benefit when
debugging – if there’s an error, there’s only one place to find it and fix it
instead of many.

Note: the underscore in _attendance denotes that the variable is protected, and
shouldn’t be modified directly. The updateAttendance() method is used to
change _attendance.

Create an object-oriented program that will have the following characteristics:


Application 
Object: House
State: Address, Color, Area
Behavior: Open door, close door

*Note: Object can be represented as a class, states as instance variables, and


behaviors as methods of your class.

Closure  Well done! You have just finished Lesson 3 of this module. Should there be
some parts of the lesson which you need clarification, feel free to ask your
teacher?
Module No. Module 1: Basic OOP Concepts
and Title 
Lesson No. Lesson 4: UML notations
and Title 
Learning Use different notations present in the Unified Modeling Language to represent
Outcomes   different OOP concepts.
Time Frame  1 hour 
Introduction This lesson will discuss what Unified Modelling Language (UML) is.

Activity Problem:

In a library, a reader can borrow up to eight books. A particular book can be


borrowed by at most one reader.

Analysis 1. With the problem above, try to develop a model that illustrates the
use of UML notations.
Abstraction  What is UML?

UML (Unified Modeling Language) is a standard language for specifying,


visualizing, constructing, and documenting the artifacts of software systems.
The Object Management Group created it (OMG), and UML 1.0 specification
draft was proposed to the OMG in January 1997. It was initially started to
capture the behavior of complex software and non-software system, and now it
has become an OMG standard.

UML is a pictorial language used to make software blueprints. It can be


described as a general-purpose visual modeling language to visualize, specify,
construct, and document software systems. Although UML is generally used to
model software systems, it is not limited to this boundary. It is also used to
model non-software systems as well—for example, the process flow in a
manufacturing unit, etc.

Goals of UML

UML diagrams are made not only for developers but also for business users,
common people, and anybody interested in understanding the system. The
system can be a software or non-software system. Thus, it must be clear that
UML is not a development method; instead, it accompanies processes to make
it a successful system.

In conclusion, UML’s goal can be defined as a simple modeling


mechanism to model all possible practical systems in today’s complex
environment.

A Conceptual Model of UML

To understandUML’se conceptual model, we need to clarify what a conceptual


model is? And why a conceptual model is required?
● A conceptual model can be defined as a model that is made of concepts
and their relationships.
● A conceptual model is the first step before drawing a UML diagram. It
helps to understand the entities in the real world and how they interact
with each other.

As UML describes the real-time systems, it is very


important to make a conceptual model and then proceed
gradually. The conceptual model of UML can be mastered
by learning the following three major elements −
● UML building blocks
● Rules to connect the building blocks
● Common mechanisms of UML
Object-Oriented Concepts

Objects are the real-world entities that exist around us, and the basic concepts
such as abstraction, encapsulation, inheritance, and polymorphism all can be
represented using UML.

UML is powerful enough to represent all the concepts that exist in object-
oriented analysis and design. UML diagrams are the representation of object-
oriented concepts only. Thus, before learning UML, it becomes important to
understand the OO concept in detail.

Following are some fundamental concepts of the object-


oriented world −
● Objects − Objects represent an entity and the basic
building block.
● Class − Class is the blueprint of an object.
● Abstraction − Abstraction represents the behavior
of a real-world entity.
● Encapsulation − Encapsulation is the mechanism of
binding the data together and hiding them from the
outside world.
● Inheritance − Inheritance is the mechanism of
making new classes from existing ones.
● Polymorphism − It defines the mechanism to exists
in different forms.

The purpose of OO analysis and design can be described


as −
● Identifying the objects of a system.
● Identifying their relationships.
● Making a design, which can be converted to executables using OO
languages.

Role of UML in OO Design

UML is a modeling language used to model software and non-software


systems. Although UML is used for non-software systems, the emphasis is on
modeling OO software applications. Most of the UML diagrams discussed so
far are used to model different aspects such as static, dynamic, etc. Now
whatever be the aspect, the artifacts are nothing but objects.

UML - Building Blocks

As UML describes the real-time systems, it is very


important to make a conceptual model and then proceed
gradually. The conceptual model of UML can be mastered
by learning the following three major elements −
● UML building blocks
● Rules to connect the building blocks
● Common mechanisms of UML

The building blocks of UML can be defined as −


● Things
● Relationships
● Diagrams

Things

Things are the most important building blocks of


UML. Things can be −
● Structural
● Behavioral
● Grouping
● Annotational

Structural Things

Structural things define the static part of the model. They represent the physical
and conceptual elements. The following are brief descriptions of the structural
things.

Class – Class represents a set of objects having similar responsibilities.

Class
Attributes
Operations
Table 1.1 Sample Model of Class

Interface – Interface defines a set of operations, which specify the


responsibility of a class.

Interface

Table 1.2 Sample Model of Interface

Collaboration – Collaboration defines an interaction between elements.

Figure 1.3 Collaboration symbol


Use Case – Use case represents a set of actions performed by a system for a
specific goal.
Use Case

Figure 1.4 Use case symbol

Component – Component describes the physical part of a system.

Figure 1.5 Component symbol

Node - A node can be defined as a physical element that exists at run time.

Figure 1.6 Node symbol

Behavioral Things

A behavioral thing consists of the dynamic parts of UML models. Following


are the behavioral things:

Interaction – Interaction is defined as a behavior that consists of a group of


messages exchanged among elements to accomplish a specific task.

Figure 1.7 Interaction symbol

State Machine – State machine is useful when the state of an object in its life
cycle is important. It defines the sequence of states an object goes through in
response to events. Events are external factors responsible for a state change.

State

Figure 1.8 State machine symbol

Grouping Things

Grouping things can be defined as a mechanism to group elements of a UML


model together. The package is the only grouping thing available for gathering
structural and behavioral things.

Package

Figure 1.9 Package symbol

Annotational Things

Annotational things can be defined as a mechanism to capture remarks,


descriptions, and comments of UML model elements. The note is the only
annotational thing available. A note is used to render comments, constraints,
etc. of a UML element.

Figure 1.10 Note symbol

Relationship

The relationship is another most important building block of UML. It shows


how the elements are associated with each other, and this association describes
the functionality of an application.

There are four kinds of relationships available.

Dependency – Dependency is a relationship between two things: change in one


element also affects the other.

Dependency

Figure 1.11 Dependency symbol

Association – Association is a set of links that connects the elements of a UML


model. It also describes how many objects are taking part in the relationship.

Figure 1.12 Dependency symbol

Generalization – Generalization can be defined as a relationship that connects a


specialized element with a generalized element. It describes the inheritance
relationship in the world of objects.
Figure 1.13 Dependency symbol

Realization – Realization can be defined as a relationship in which two


elements are connected. One element describes some responsibility, which is
not implemented, and the other one implements them. The relationship exists in
the case of interfaces.

Figure 1.14 Realization symbol

UML Diagrams

UML diagrams are the ultimate output of the entire discussion. All the
elements, relationships are used to make a complete UML diagram, and the
diagram represents a system.

The visual effect of the UML diagram is the most important part of the entire
process. All the other elements are used to make it complete.

UML includes the following nine diagrams:


● Class diagram
● Object diagram
● Use case diagram
● Sequence diagram
● Collaboration diagram
● Activity diagram
● Statechart diagram
● Deployment diagram
● Component diagram

UML - Architecture

Different users use any real-world system. The users can be developers, testers,
business, people, analysts, and many more. Hence, before designing a system,
the architecture is made with different perspectives in mind. The most
important part is to visualize the system from the perspective of different
viewers. The better we understand, the better we can build the system.

UML plays an important role in defining different


perspectives of a system. These perspectives are −
● Design
● Implementation
● Process
● Deployment
The center is the Use Case view, which connects all these four. A Use Case
represents the functionality of the system. Hence, other perspectives relate to
the use case.

The design of a system consists of classes, interfaces, and collaboration. UML


provides a class diagram, object diagram to support this.
Implementation defines the components assembled to make a complete
physical system. A UML component diagram is used to support the
implementation perspective.
The process defines the flow of the system. Hence, the same elements as used
in Design are also used to support this perspective.
Deployment represents the physical nodes of the system that forms the
hardware. A UML deployment diagram is used to support this perspective.

UML - Modeling Types

Structural Modeling

Structural modeling captures the static features of a system. They consist of the
following:
✔ Classes diagrams
✔ Objects diagrams
✔ Deployment diagrams
✔ Package diagrams
✔ Composite structure diagram
✔ Component diagram
The structural model represents the framework for the system, and this
framework is where all other components exist. Hence, the class diagram,
component diagram, and deployment diagrams are part of structural modeling.
They all represent the elements and the mechanism to assemble them.

The structural model never describes the dynamic behavior of the system. The
class diagram is the most widely used structural diagram.

Behavioral Modeling

The behavioral model describes the interaction in the


system. It represents the interaction among the
structural diagrams. Behavioral modeling shows the
dynamic nature of the system. They consist of the
following −
✔ Activity diagrams
✔ Interaction diagrams
✔ Use case diagrams
All the above show the dynamic sequence of flow in a system.

Architectural Modeling

The architectural model represents the overall framework of the system. It


contains both structural and behavioral elements of the system. The
architectural model can be defined as the blueprint of the entire system. The
package diagram comes under architectural modeling.

UML - Basic Notations

UML notations are the most important elements in modeling. Efficient and
appropriate use of notations is very important for making a complete and
meaningful model. The model is useless unless its purpose is depicted properly.

Hence, learning notations should be emphasized from the very beginning.


Different notations are available for things and relationships. UML diagrams
are made using the notations of things and relationships. Extensibility is
another important feature that makes UML more powerful and flexible.

Structural Things
Graphical notations used in structural things are most widely used in
UML. These are considered as the nouns of UML models. Following is the list
of structural things.
✔ Classes
✔ Object
✔ Interface
✔ Collaboration
✔ Use case
✔ Active classes
✔ Components
✔ Nodes

Class Notation

The following figure represents the UML class. The diagram is divided into
four parts.
✔ The top section is used to name the class.
✔ The second one is used to show the attributes of the class.
✔ The third section is used to describe the operations performed by
the class.
✔ The fourth section is optional to show any additional
components.
Figure 1.15 Sample Class Diagram

Object Notation

The object is represented in the same way as the class. The only difference is
the name which is underlined, as shown in the following figure.

Figure 1.16 Sample Class Diagram


As the object is an actual implementation of a class, known as the instance of a
class, it has the same usage as the class.

Interface Notation

The interface is represented by a circle, as shown in the following figure. It has


a name which is generally written below the circle.

Figure 1.17 Sample Interface Notation

The interface is used to describe the functionality without implementation. The


interface is just like a template where you define different functions, not the
implementation. When a class implements the interface, it also implements the
functionality as per requirement.
Collaboration Notation
Collaboration is represented by a dotted eclipse, as shown in the
following figure. It has a name written inside the eclipse.

Figure 1.18 Sample Collaboration Notation

The collaboration represents responsibilities. Generally, responsibilities are in a


group.

Use Case Notation


The use case is represented as an eclipse with a name inside it. It may
contain additional responsibilities.

Figure 1.19 Sample Use Case Notation

A use case is used to capture high-level functionalities of a system.

Actor Notation
An actor can be defined as an internal or external entity that interacts with the
system.

Figure 1.20 Sample actor notation


An actor is used in a use case diagram to describe the internal or external
entities.

Initial State Notation

The initial state is defined to show the start of a process. This notation is used
in almost all diagrams.
Figure 1.21 Sample initial state notation

Final State Notation

The final state is used to show the end of a process. This notation is used in
almost all diagrams.

Figure 1.22 Sample final state notation

Active Class Notation

The active class looks like a class with a solid border. Active class is generally
used to describe the concurrent behavior of a system.

Figure 1.22 Sample active class notation

Active class is used to represent the concurrency in a system.

Component Notation

A component in UML is shown in the following figure with a name inside. A


component is used to represent any part of a system for which UML diagrams
are made. Additional elements can be added wherever required.

Figure 1.23 Sample component notation

Node Notation

A node in UML is represented by a square box shown in the following figure


with a name. A node represents the physical component of the system. It is
used to represent the physical part of a system such as a server, network, etc.
Figure 1.24 Sample node notation

Interaction Notation

Interaction is a message exchange between two UML components. Interaction


is used to represent the communication among the components of a system.

Figure 1.25 Sample interaction notation


State Machine Notation

State machine describes the different states of a component in its life cycle. It is
used to describe different states of a system component. The state can be active,
idle, or any other depending upon the situation.
Figure 1.26 Sample state machine notation

Package Notation

Package notation is shown in the following figure and is used to wrap the
components of a system.

Figure 1.27 Sample package notation

Node Notation

Node notation is used to provide necessary information about a system.

Figure 1.28 Sample note notation

Relationships

A model is not complete unless the relationships between elements are


described properly. The Relationship gives a proper meaning to a UML model.

Following are the different types of relationships in UML:


● Dependency
● Association
● Generalization
Dependency Notation

Dependency is an important aspect in UML elements. It describes the


dependent elements and the direction of dependency. It is represented by a
dotted arrow as shown in the following figure. The arrowhead represents the
independent element and the other end represents the dependent element.

Figure 1.29 Sample dependency notation

Dependency is used to represent the dependency between two elements of a


system.

Association Notation

Association describes how the elements in a UML diagram are associated. In


simple words, it describes how many elements are taking part in an interaction
—a dotted line with (represents it without) arrows on both sides. The two ends
represent two associated elements, as shown in the following figure. The
multiplicity is also mentioned at the ends (1, *, etc.) to show how many objects
are associated.

Figure 1.30 Sample association notation


Association is used to represent the relationship between two elements of a
system.

Generalization Notation

Generalization describes the inheritance relationship of the object-oriented


world. It is a parent and child relationship. It is represented by an arrow with a
hollow arrowhead, as shown in the following figure. One end represents the
parent element, and the other end represents the child element.
Figure 1.31 Sample generalization notation
Generalization is used to describe the parent-child relationship of two elements
of a system.

Application  From your experience, try to develop a model that illustrates the use of the
following UML notation elements:
● Dependency
● Association
● Generalization

For this activity, concentrate on the relationships between classes rather than
the details of their members. Explain and discuss your model with your teacher.

Well done! You have just finished Lesson 4 of this module. Should there be
Closure  some parts of the lesson which you need clarification, feel free to ask your
teacher?
Module No. Module 1: Basic OOP Concepts
and Title 
Lesson No. Lesson 5: Creating class diagrams
and Title  Lesson 6: Representing inheritance, association, and composition

Learning - Understand the importance of creating graphical models of classes in


Outcomes   OOP.
- Create class diagrams using the Unified Modeling Language.

Time 2 hours
Frame 
Introduction This lesson will discuss the importance of creating graphical models of classes
in OOP using class diagrams.

Activity Consider the Student and Course Class relationships with the following
constraints:

1. Each Course object maintains a list of the students on that course and
the lecturer who has been assigned to teach that course
2. The Course object has a behavior that allows the adding and removing
of students from the course, assigning a teacher, getting a list of the
currently assigned students, and the currently assigned teacher.
3. Teachers are modeled as Lecturer objects. As a lecturer may teach more
than one course, there is an association between Course and Lecturer.
The “taught by” relationship shows that a Course only has a single
teacher, but that a lecturer may teach several Courses.
4. Each Lecturer object also maintains a list of the Courses that it teaches.
5. There is a similar relationship between Course and Student. Zero or
more Students attend a course, and a Student may attend multiple
courses.

Analysis 1. Create a Class Diagram of the problem above.

Abstraction  What is the Class Diagram?

Class diagrams describe the system’s structure by showing the system’s


classes, their attributes, and the relationships among the classes.

A UML class diagram is a picture of


• the classes in an OO system
• their fields and methods
• connections between the classes that interact or inherit from each other

Not represented in a UML class diagram:


• details of how the classes interact with each other
• algorithmic details: how a particular behavior is implemented

Diagram of a single class

Class name
• write «interface» on top of interfaces' names
• use italics for an abstract class name
Attributes (optional)
• fields of the class
Operations / methods (optional)
• may omit trivial (get/set) methods
• but do not omit any methods from an interface!
• should not include inherited methods
(a) (b)
Figure 1.32 Sample class diagram for Rectangle and Student class.

Class operations / methods

Syntax:
visibility name(parameters): return_type
1. visibility
+ public
# protected
- private
~ package (default)
2. parameters listed as name: type
3. underline static methods
4. omit return_type on constructors and when return type is void

Comments

Comments are represented as a folded note, attached to the appropriate


class/method/etc. by a dashed line.

Figure 1.33 Sample comment in the class diagram.

Relationships between classes


Generalization is an inheritance relationship
● inheritance between classes
● interface implementation

Association is a usage relationship


● dependency
● aggregation
● composition

Generalization relationships

1. Hierarchies drawn top-down


2. Arrows point upward to parent
3. Line/arrow styles indicate if parent is a(n):
• class: solid line, black arrow
• abstract class: solid line, white arrow
• interface: dashed line, white arrow
Figure 1.34 Sample class diagram for generalization relationship

Associational (usage) relationships

1. Multiplicity (how many are used)


● (zero or more)
● 1 (exactly one)
● 2..4 ( between 2 and 4, inclusive)
● 3..* (3 or more, * may be omitted)

2. Name (what relationship the objects have)


3. Navigability

Figure 1.35 Sample class diagram for generalization relationship

Association multiplicities

1. One-to-one
● Each car has exactly one engine.
● Each engine belongs to exactly one car.
2. One-to-many
● Each book has many pages.
● Each page belongs to exactly one book.
Figure 1.36 Sample class diagram for association relationship

Example 1:

Example 2:

Association Types

1. Aggregation: “is part of”


● Symbolized by a clear white
diamond
2. Composition: “is entirely made of”
● the stronger version of aggregation
● the parts live and die with the
whole
● symbolized by a black diamond
3. Dependency: “uses temporarily.”
● symbolized by the dotted line
● often, is an implementation detail,
not an intrinsic part of the object’s state

Example:
Inheritance

Aside from associations, the other main modeling relationship is inheritance.

In the example above, Class A ‘inherits’ both the interface and implementation
of Class B.

Example: Inheritance

Consider books and magazines – both specific types of publications.

We can show classes to represent these on a UML class diagram. In doing so,
we can see some of the instance variables and methods these classes may have.

Book Class

Attributes ‘title’, ‘author,’ and ‘price’ are obvious. Attribute ‘copies’ signifies
how many books are currently in stock.

orderCopies() takes a parameter specifying how many copies are added to


stock.

Magazine Class

orderQty is the number of copies received of each new issue, and currIssue is
the date/period of the current issue. When a newIssue is received, the old is
discarded, and orderQty copies are placed in stock. Therefore, recvNewIssue()
sets currIssue to date of the new issue and restores copies to orderQty.
adjustQty() modifies orderQty to alter how many copies of subsequent issues
will be stocked.

Problem:
Look at the Book and Magazine classes and identify the commonalities and
differences between the two classes.

Solution:
These classes have three instance variables in common: title, price, copies.
They also have in common, sellCopy().

The differences are as follows…

Book additionally has authors and orderCopies().


Magazine additionally has orderQty, currIssue, adjustQty() and
recvNewIssue().

We can separate these common members of the classes into a superclass called
Publication.

The differences will need to be specified as additional members for the subclass
Book and Magazine.
The hollow-centered arrow denotes inheritance.

Note that the Subclass has the generalized superclass characteristics +


additional specialized characteristics. Thus, the Book class has four variables
(title, price, copies, and author). It also has two methods (sellCopy() and
orderCopies()).

The inherited characteristics are not listed in the subclass. The arrow shows
they are acquired from the superclass.

Class Diagram Example 1


Unidirectional association –
one class is aware of the
other and interacts with it.
Class Diagram Example 2: people

Class Diagram Example 3: student

When to/not to Use Class Diagrams?

Class diagrams are great for:


✔ discovering related data and attributes
✔ getting a quick picture of the important entities in a system
✔ seeing whether you have too few/many classes
✔ seeing whether the relationships between objects are too complex, too
many, simple enough, etc.
✔ spotting dependencies between one class/object and another

Not so great for:


✔ discovering algorithmic (not data-driven) behavior
✔ finding the flow of steps for objects to solve a given problem
✔ understanding the app's overall control flow (event-driven? web-based?
sequential? etc.)

Activity Create a Class Diagram of an Online Shopping System

Each customer has a unique id and is linked to exactly one account. The
account owns a shopping cart and orders. The customer could register as a web
user to be able to buy items online. A customer is not required to be a web user
because purchases could also be made by phone or by ordering from catalogs.
The web user has a login name, which also serves as a unique id. Web users
could be in several states - new, active, temporary blocked, or banned, and
linked to a shopping cart. The shopping cart belongs to the account.

The account owns customer orders. The customer may have no orders.
Customer orders are sorted and unique. Each order could refer to several
payments, possibly none. Every payment has a unique id and is related to
exactly one account.

Each order has a current order status. Both order and the shopping cart have
line items linked to a specific product. Each line item is related to exactly one
product. A product could be associated with many line items or no item at all.

Well done! You have just finished Lesson 5 and 6 of this module. Should there
Closure  be some parts of the lesson which you need clarification, feel free to ask your
teacher?

Module No. and Title 1.Basic OOP Concepts


Lesson No. and Title 2. Creating classes and objects
Learning Outcomes Differentiate classes, objects, static variables, and instance variables.
Time Frame 1 day
Introduction This lesson will introduce the application of objects inside a class. It is
discussed in the previous lesson the difference between procedural and
object-oriented programming. Objects, as part of a class, plays an important
role in heavy object-oriented programming languages like java to create
useful programs. It is a basic building block in an object OOP language (like a
brick to build a house). Our discussion may use real-world objects to help you
better understand the topic. With the knowledge you now have of the basics
of the Java programming language, you can learn to write your own classes. In
this lesson, you will find information about defining your own classes and
creating an object. After the discussion, you are expected to create your own
simple program applying the lessons you have learned.
Activity Work by pair to encourage peer to peer sharing of ideas and understanding
throughout the duration of the abovementioned lesson.
To better understand the topic, let us begin the lesson with giving examples of
real-world object. With your pair, utilize the table below. Fill the first column
with an object you can see inside the school campus. Second, write the
qualities of the object you have chosen. Third, specify your chosen object’s
behavior or the task it is able to perform.

Object Qualities Behavior


1. 1. 1.
2. 2. 2.

Analysis With the knowledge you now have of the basics of the Java programming
language, answer the following:
1. What is a class?
2. What is the difference between procedural and object-oriented
programming?
3. What do you think is the role played by objects in a class?

Abstraction 2. CLASSES AND OBJECTS


Java is an object-oriented programming language that is always associated
with classes and objects. In java, classes serve as blueprint for creating objects
which hold its own members while objects are instances of a class. It may
represent a real-world entity that has characteristics and can perform tasks.
With OOP approach, it allows you to dvide complex problems into smaller sets
by creating objects.

2.1. CLASS
A class is a user defined blueprint or prototype from which objects are
created. It represents the set of properties or methods that are common to all
objects.
Syntax:
To create a class in java, one must simply
declare a class name followed by an open and
close bracket as seen in the picture.
The name of the class is “MyClass”.

Figure 2.1.1 - MyClass

2.2. OBJECT
To better understand objects, software objects are conceptually similar to
real-world objects: they too consist of state and related behavior. An object
stores its state in fields/attributes (variables in some programming languages)
and exposes its behavior through methods (functions in some programming
languages). Objects in java is also known as instance of the class.

Consider a bicycle, for example:


It has state (fields/Attributes) which among others
are: color, price, height.
It also has behavior (Method) like changing gears,
accelerating, etc.

Figure 2.2.1

Creating an object from a class must specify the class name which is then
followed by the object’s identifier (variable) and the keyword “new”. The
sample below shows how to create or declare an object:

Syntax:

Figure 2.2.2
“Bike” is now an object/instance of the class “MyClass” created inside the
class “MyClass” in line number 6.
To use the attribute “bikeName”, append the attribute’s name/variable to the
object reference with an intervening dot operator(.) as shown in line number
8.
2.3. INSTANCE AND STATIC VARIABLES
We are done with creating an instance of a class (object) in a class, and we
need variables as storage of information that will define our object.
Java variables, in simplest term, are used to store data which java program
needs to perform its job. An instance variable is variable that needs to be
appended to the object reference with an intervening dot operator while
static variable is a variable that can be accessed at any point of the class
without the need to append it to the object reference.

Notice how the static variable “price”


is used to change its state/ current
value from “3000” to “5000” in line
100. The “price” is appended to the
object reference “bike” with an
intervening dot operator
Figure 2.2.3 – Instance Variable
Static variables are variables that could be called to any point of the program
without the need to append it in the object reference, provided, however,
that it meets the requirements of static variable’s access modifier.
Figure 2.2.4 – Static Variable

Application Create a simple java program that declares an object whose name is “myself”.
The program should print at least 2 qualities of the object you have created.
It should apply the concepts of static and instance variables as discussed
above.
The first quality should be stored in a static variable while the second should
be in an instance variable.

Sample output:
Beautiful
Smart
Closure If you have successfully created a java program that has carried out the
output specified, congratulations! Continue improving yourself and always
work with your peer to share and gain more ideas.
The topics discussed in this module will be useful in the upcoming lessons, so
make sure to revisit and remember this topic.

Module No. 1. Basic OOP Concepts


and Title
Lesson No. 3. Attributes, Methods, Constructor and Destructors
and Title
Learning ● Differentiate static methods and instance methods.
Outcomes ● Differentiate attributes and methods in their own created classes.

Time Frame 3 days.


Introduction This lesson will help you better understand the implementation of attributes and
methods in a program. Now you will learn and enumerate the parts of the method
and their corresponding role upon the method’s execution; Trace the program flow
execution; Learn how to invoke methods with or without instance of a class and
parameters. Expect that at the end of the topic you will be identifying and debugging
semantic and syntax errors of a program that implements the syntaxes covered in this
lesson.
Activity Create a java program that contains the following:
1. an instance of a class.
2. a static variable.
3. a static method.
4. An instance variable
5. An instance method

Analysis Questions:
1. What is/are the difference/s between static methods and instance methods?
2. What is/are the difference/s between static variables and instance variables?
3. How does invoking/ calling process takes place for static variables and/ or
method?

Abstraction 3. ATTRIBUTES AND METHODS


Attributes and methods are among the two important class members that work with
the class’ object. Although an attribute is a vague term, let’s focus on attributes that
are instantiated inside the class that hold a value representing the object’s
characteristics or qualities. Remember that an object, as discussed in previous topic,
could be a real-world entity, thus, attributes may refer to the set of features that
describes it entity or the object. On the other hand, A method is a class member
which performs specified operations. In OOP, methods are procedures that defines
the behavior in which an object is able to perform.

3.1. ATTRIBUTES
Syntax:

As discussed in the previous lesson, there are two (2) types of variables – Static and
instance. Attributes and variables, though oftentimes used interchangeably, slightly
differs from each other. An attribute in object-oriented programming is a field that
defines the object in a class while a variable is a general term that holds values
including those that are not related to the object. Thus, both static and instance are
variables, however, in OOP languages, instance variables are attributes while static is
not. To make it more coherent, take the declaration of variables and attributes below.
DECLARING ATTRIBUTES VS DECLARING VARIABLE

Figure 3.1.0 – Declaring variable

Figure 3.1.1 – Declaring attribute


The static keyword indicates that the variable can be accessed at any point of the
program without an object, provided however, that it meets the specifications of its
access modifier. On the other hand, attributes don’t have the “static” keyword upon
its declaration and can only be called by appending it to the object reference with an
intervening dot (.) operator.

Example (Attribute):

Notice how the attribute


whose name is “color” is
appended to the object
reference “bike”. Thus, it is
an attribute that gives
qualities to our object “bike”
Figure 3.1.2 – Declaring attribute

In the sample code, the variable color is attributed to our object (Bike), thus, object’s
Bike color now is “Blue” and will print an output “Blue”.
3.2 CREATING METHODS

Figure 3.2.0
– Parts of a Method
The picture above shows how to create a method with their parts being labelled.
These parts have their corresponding functions on or before the method’s execution.
1. Access modifier – determines the method’s accessibility to other members of
the class and/or other inherited class.
2. Return type – Should be explicitly specified when declaring a method since
this will determine what data type to be return. A return type could be
primitive type or void type (returns nothing).
3. Method name/Identifier –can be used when the method needs to be invoked
at any point in program by calling method name.
4. Parameter list/s – also known as arguments which specify what type of data a
method can receive.
5. Method body – defines whole method itself. This is where the set of
operations and algorithms are located and are performed during its
execution.

Putting and algorithm in a method for reusability


3.3. Method Calling
Note that there are static and instance methods. They differ upon method’s calling.
Static methods can be easily identified because of keyword “static” after the
method’s modifier. Take the examples below.

Figure
3.3.0. – Instance method Figure 3.3.1. – Static method

Figure 3.3.0 is instance method which requires an instance of a class (object) for it to
be accessed while figure 3.3.1 is a static method, because of the static keyword,
which can be access at any point of the class without an instance (Object).
Example:
Figure 3.3.2. – Sample Code
The picture above shows the implementation of static and instance methods. Notice
how instance method is invoked in line 62 compared to static method in line 60.
Methods without a static keyword needs to be appended to the object reference with
an intervening dot operator (line 62) while static methods can be called without the
need to append the object reference (line 13).

Again, an identifier should be invoked to call a method so as to perform the operation


inside its body. When a method is called, the program control gets transferred to the
called method and goes back to the caller after meeting the two conditions:
1. After the getting the return statement; and
2. Reaches the end of the called method.

Example:
Figure 3.3.3 below illustrates the execution flow after calling a method. Line 60 calls
the static method, performs its specified operation then goes back to the caller. Same
flow applies to the calling process of an instance method in line 62.

Figure 3.3.3. – Execution Flow


On the other hand, observe how
“myPublicMethod()” method In the figure 3.3.3. returns a value that correspond to its
primitive return type in line 55. It returns a value of 1 (line 56) since the data type
specified in the return type is int which means integer, thus, satisfying the first(1 st)
condition. Meanwhile, the “myStaticMethod” returns no value until it reaches the
end of the method since it is a void type because of the keyword “void”, thus,
satisfying the second(2nd) condition.

3.4. METHOD PARAMETER/S


Parameters or arguments exist inside and open and close parenthesis after the
method’s name. Methods can take many parameters. However, please note that
when invoking methods, the caller’s parameter should match the called method in
terms of:
a. Number of parameter/s
b. Order of the Data type (If there are multiple parameters).

3.5. CONSTRUCTORS
Methods and attributes as mentioned above are essential class members of the
object-oriented programming. A method is a class member which performs specified
operation that defines the behavior of an object. A constructor, is also a method that
performs specified operation; however, it can only be invoked when an object in a
class is created.

Example:

The picture above shows how the constructor “MyClass” is created and is used to
change the initial value of the attribute “color”. When an object is created, the
constructor is invoked changing the value of the attribute “color” from “none” to
“blue”.

Remember:
● Constructors’ name must match the class name and it cannot have any return
type.
● Constructors are always called whenever an object is created.
● Java will create a default constructor if you do not create one, setting the
instantiated attributes into its primitive data type’s default value.

CONSTRUTOR PARAMETERS
Constructors can also take parameters. However, one should always remember that
the number of parameters including their data type in a constructor match the
number of parameters specified in the created instance of a class.
Notice that the object bike contains one String parameter whose value is “BMW”,
thus, the constructor “MyClass” should also have one String parameter as shown in
the above picture.
Another thing to remember is that the order of data type of parameters in the object
should also match the order of data type of parameters in the constructor.
Example:

The created object “bike” has two (2) parameters, “BMW’ and 8500, thus, the
constructor should also have the same order of parameters in terms of data type. As
shown in the above picture, constructor “MyClass” contains two parameters with
data type “string” and “int” which both conforms to the order of data type in the
object.

DESTRUCTORS
Destructor is a method called when the destruction of an object takes place. The
main goal of the destructor in general is to free up the allocated memory and also to
clean up resources like the closing of open files, closing of database connections,
closing network resources, etc. Although, there is no documented destructor in java
programming language unlike C++, java has garbage collector where developers can
free resources and save garbage collector’s work.
● How important is destructor?

When java programs run on the Java Virtual Machine, objects are created on the
heap taking up space and allocation in the memory dedicated only for the program.
Eventually some of these programs are no longer needed, thus, we need destructors
to free up the heap or the allocated space intended for the java program.
● What is a garbage collector?

A garbage collector automatically manages the application’s dynamic memory


application requests and performs automatic dynamic memory management through
allocating from and giving memory back to the operating system, handing out
memory to the application as it requests it, determining which parts of that memory
is still in used by the application, and reclaims the unused memory for reuse by the
application.
● How does java garbage collection works?
JVM implements garbage collection however it please as long as it meets the JVM
specifications. The most common JVM used by far is Oracle which deploys multiple
garbage collection.

Application It’s urgent!


Please help Tom identify and change the error/s from the program below so that it
will provide an output “Congratulations! For debugging the program successfully” in
just 30 mins so that he can save the world!

Closure Thanks for helping Tom out! You really are great! Thanks for the help in saving the
world!

Module No. 1. Basic OOP Concepts


and Title
Lesson No. 6. The Exception Class Heirarchy
and Title
Learning Use of Exception handling.
Outcomes
Time Frame 3 days
Introductio This lesson will introduce the important feature of java programming that allows us to
n handle the runtime errors caused by exceptions. We will learn what is an exception,
types of it, exception classes and how to handle exceptions in java with examples.
Expect that at the end of this lesson you will create your own java program that will
implement the use of basic exception handling.
Activity Before we begin, open a PC or laptop and perform the following:
A. Compile a java program with semantic errors; and
B. Run multiple computer application simultaneously in your computer system
until one of these programs will no longer respond due to runtime error.

Analysis A. Running a Java program with semantic errors.


1. What happens to the flow of execution when you compile a java program with
semantic errors?
2. When you compile a java program with semantic errors, will the rest of the
code execute properly or will it get terminated in the block with error?
B. Running multiple computer application.
1. Upon running multiple applications in your computer system until one of them
no longer respond, are there any message the computer operating system has
prompted?

Abstraction 6. EXCEPTION CLASS HEIRARCHY


What is an Exception?
When there occurs an unexpected event during the execution of the program that will
disrupt the normal flow of the execution, e.i, run time or semantic errors, the program
should, at all cost, proceed with its intended process as it is. These disruptions,
however, should be handled and should be prompted back to the user informing them
that certain conditions have occurred and that indicates that these conditions should
be caught. This is the purpose of exception handling.

In java, exceptions is organized in a hierarchy. The throwable class, which is an


immediate subclass of object, has two subclasses of exception in the heirarchy –
exception and error. See Figure 6.1

Figure 6.1 – Exception Class Hierarchy Diagram


As illustrated in the above figure, both error and exception are immediate subclass of
the throwable class. These two subclasses have their corresponding subclasses as
defined in the java.lang package.

Figure 6.2 – Java Error classes Figure 6.3 –Java Exception classes
We will narrow down our lesson and focus on the exception class hierarchy (figure
6.3).
To prevent a program execution to stop in a certain line, one must anticipate and
consider handling abnormal conditions. These conditions are being represented by
standard exception classes. Consider the example code below.

The sample program above contains a semantic error that will cause the termination of
the execution flow of the program. Length of a String primitive data type cannot be
counted if it contains null value (this occurs when users try to input nothing in a field).
Without exception handling, it will provide the sample code will terminate the flow of
execution.
How to handle exception?
Basically, we wouldn’t want our code to abnormally terminate because of any reasons.
Java has essential customized keywords upon handling exceptions – try, catch, throw,
and finally. These keywords have their own blocks and role in handling exceptions. Try
block is where program statements are being contained. If by any chance exception
occurs within the try block, your code can throw the exception into the catch block and
handle it in some rational manner without the JVM terminating the execution of the
program. These exception is thrown outside the try block and could also be prompted
as such to users to identify the line/s with exception. Finally block must be executed
after try block is completed.
Consider this example:

The program contains semantic error trying to access the index 4. Knowing that
indexes of array starts at 0, the above example array is already defined with a length of
4. In this case, it will throw and exception and will terminate the flow of execution in
the line “int I = arr[4];”. To fix it, we need to catch the exception and throw it so that
the “Hi, I want to execute” will be executed.

There are lots of exception


handling syntax in java that throws exception and that would require longer time to
discuss. Take and spend more time to learn and read them over the internet.

Points to remember:
1. In a method, statements should be put in its own try block and provide
exception handlers since there can be many statements that might throw
exception.
2. One can specify the exception handler in the catch block provided however,
that the exception specified is associated with the exception of the program
statement within the try block. There can be more than one catch block to
catch possible exceptions indicated by its argument and must be the name of
the class that inherits from the throwable class.
3. There can only be one finally block. Try blocks can have zero or more catch
blocks.
4. Finally block will always be executed whether or not the try block contains
exceptions. If by any chance try block contains exceptions, finally block will be
executed after the catch block. Finally block is used commonly in cleaning up
codes.

Application Create a java program that will implement the use of exception handling. You can
choose what exception to be handled as long the flow of execution will continue until it
reaches the end of the program. Remember to apply the basics of object-oriented
programming concepts.
Closure Congratulations for reaching the end of basic OOP concepts!

References:

REFERENCES:

1. Kendal, Simon (2009). Object-Oriented Programming using Java. Simon Kendal &
Ventus Publishing ApS
2. Poo, Danny. et.al. (2008). Object-Oriented Programming and Java. Second Edition.
Springer-Verlag London Limited.
3. What is Object-Oriented Programming? OOP Explained in Depth(2020). Retrieved from:
https://www.educative.io/blog/object-oriented-programming
4. Object-Oriented Programming Language (OOPL) (2020). Retrieved from:
https://www.techopedia.com/definition/8641/object-oriented-programming-language-
oop1
5. Fowler, Martin(2004).UML Distilled: A Brief Guide to the Standard Object Modeling
Language. Pearson Education, Inc.
6. Farrel, Joyce (2012). Java Programming
7. Geeksforgeeks.com (2018). “Errors V/s Exceptions in Java” retrieved from
https://www/google.coom/url?sa=t&sources=web&rct=j&url=https://www.geeksforgeeks
.org/errors-v-s-exceptions-in-java/amp/
&ved=2ahUKEwiw5uhJ2lvrAhXgw4sBHbFEBB4QFjAQegQIARAB&usg=AOvVAW2
QCyyUHL4XGlls0wpUGC8j&ampcf=1
MODULE SUMMARY
This module introduces the fundamental concepts, theories, and applications of object-oriented
approach in java programming language that will help participants better understand and apply the
difference between the traditional or procedural from object-oriented approach and encouraging
participants to implement important class members and program structure that demonstrate the
concepts of OOP. It will also include creating unified diagrams that represents entities and their
corresponding associations based from the setup of real-world scenario. In general, this module
presents the sequential method of understanding the real-world concepts and their application into
object-oriented programming concepts and structure.

At the end of every topics in this module, participants must undergo several activities to enable them to
utilize the general knowledge they have gained and to exercise their comprehension.

The following are the key important information that were focused in this module:
1. Object-oriented programming involves the creation of objects that model a business
problem you are trying to solve.
2. In creating an object-oriented program, you define the properties of a class of objects and
then create individual objects from this class.
3. Object-oriented principles involve abstraction, encapsulation, inheritance and
polymorphism.
4. The procedural approach to programming was the de facto approach in the early days of
programming. Here, code is modularized based on a system’s processes.
5. Object-oriented programming, on the other hand, models objects and their interactions in
the problem space and the production of a system based on these objects and their
interactions.
6. Object-oriented programming language (OOPL) is a high-level programming language
based on the object-oriented programming (OOP) model.
7. Classes are where the programmer creates a blueprint for the structure of methods and
attributes.
8. Objects are instances of classes created with specific data.
9. Attributes are the information that is stored.
10. Methods perform actions; methods might return information about an object, or update an
object’s data.
11. UML (Unified Modeling Language) is a standard language for specifying, visualizing,
constructing, and documenting the artifacts of software systems.
12. Class diagrams describe the system’s structure by showing the system’s classes, their
attributes, and the relationships among the classes.
MODULE ASSESSMENT
Choose only the letter of the correct answer.
1. A function which has the same name of the class which could be used for initialization of the uninitialized
instance variables.
a. Constructor c. Object
b. Method d. class
2. A word used to describe a block of code that will be executed whenever there is an object instantiation.
a. Method c. Object
b. Constructor d. Object Oriented Program
3. Java compiler distinguishes a constructor from a method using _____ and ______.
a. Datatype; access modifier c. Parameter; object
b. Identifier; return type d. Constructor name; parameter
4. This refers to the part of a method block which will set the visibility of the function or the method itself.
a. Static Keyword c. Access Modifier
b. Visibility Modifier d. Method Block
5. _________ is a Jargon used for function. They are bound to a class, define the behavior of a class and
performs specific task indicated by the user.
a. Algorithm c. Constructor
b. Method d. Object
6. A part of a method block which defines what the method actually does and how the variables are
manipulated.
a. Access Modifier c. Method Block
b. Return type d. Method’s task
7. Refers to the part of a method block which is used as an identifier.
a. Method Name c. Method Body
b. Access Modifier d. Return type
8. Which of the following best describes an instance variable?
a. These are variables that are declared outside any of methods, constructors, and or classes.
b. These are variables whose lifetime varies with the execution of a method or constructor block.
c. These are variables that may be static or non-static having its value initialized as default.
d. These are variables that are inside the class but outside any methods or constructors.
9. Which of the following best describes a local variable?
a. These are variables that are declared outside any of methods, constructors, and or classes.
b. These are variables whose lifetime varies with the execution of a method or constructor block.
c. These are variables that may be static or non-static having its value initialized as default.
d. These are variables that are inside the class but outside any methods or constructors.
10. Which of the following is true for a static variable?
a. Static variable is a variable that needs class instantiation to be used.
b. This is variable whose lifetime varies with method or constructor block execution.
c. Variables that can be accessed by any method or constructor.
d. These are variables that should be declared inside a method or constructor and should have
static keyword.

B.

1. Create an algorithm that will print any square value of an “int” input (specified by the user) using a static
void type of method whose access modifier is set to private.
2. Create a constructor, whose parameter is only one, that will automatically twice the value of the int
argument of a class instance.
3. Using the program structure you created in number 2, draw lines to illustrate the execution flow of
compiling a java program.

You might also like