Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 103

CSC 233:

Object-Oriented Programming
3 Credits

Amos O. Bajeh, PhD


Course Content
OOP principles: Abstraction, encapsulation and
Information hiding, inheritance, and polymorphism.
Class, Objects, properties and methods. Relationship
between classes and class hierarchy. Abstract
classes. Interface. Class Libraries. Object-oriented
design approach/object modeling: identification of
classes, class attributes and methods in problem
statements
OOP Concepts
 Object-Oriented programming (OOP) is a programming
paradigm/methodology that involves using objects to
model the solution for a programming task.
 An object represents an entity in the real world that can
be distinctly identified. E.g., a student, a desk, a circle,
a button, and even a loan, bank account, course
OOP Concepts
 Objects and Classes

 An object has properties and behaviors

 Properties (attributes) describes the state of an


object. It consists of a set of data fields with their
current values which define the state of the object.

 Behavior (methods) of an object is defined by a


set of operations that the object can perform or
that can be performed on the object.
 Classes are group of objects with similar
attributes and behaviors:

 People,books,dogs,cats,cars,airplanes,trains,etc.

 An instance of a class is an object


e.g. Adams, thing Fall apart, Bingo, Honda Accord 2010,
etc.

Thus,
 A class I a blueprint for the creation of objects
Principles of OOP
 Abstraction
 Encapsulation and information hiding
 Inheritance
 Polymorphism
OOP vs Structured Programming
Object-oriented Procedural
Bottom-up approach Top-down approach
Divide into objects Divide into functions
Objects communicate Data can be passed from
through methods one function to another

More secure Less secure


Java Installation

https://www.oracle.com/technetwork/java/javase/downloads/index.html

Click on the Download button


Java Installation

Accept license agreement and click on the product that fits your machine to
download

Install it on your machine


Java Installation
IDE:
•eclipse:
https://www.eclipse.org/downloads/packages/
Java Installation
IDE:
•NetBean : https://netbeans.org/downloads/8.2/
Fundamentals of Java
 How Java gets Executed

Source Java Byte Machine


Code Compiler: Code code

.java jdk .class virtual


machine
Fundamentals of Java
 Character set:
the set of characters recognized by the language. Java
recognizes the following set of character sets.
Alphabets: Unicode: Alphabets, digits and other special
characters in almost all human languages
Escape Sequence: multi-character starting with a
backslash and denotes an action
\n newline
\b backspace
\t tab
Fundamentals of Java
 variable:
a program entity whose value can change or be altered
during the course of program execution

 constant: a program entity whose value cannot be changed


or altered during the course of program execution
 Identifiers: names given to program entities e.g. names of variables, constants and
methods.

 Rules and conventions for Identifiers:


 Anylength of Unicode letters and digits but must begin with an alphabet, $, or _
 Subsequent characters can be letters, digits, $ or _
 Must NOT be a keyword or reserved words

 Always start your identifiers with letter, seldom use $ or _ to start your identifiers
 Use full words instead of cryptic; to enhances understandability
 Use camelCase: In Identifiers with more than one word, start other words with uppercase letters
except the first word
 Data Types: Primitive and Composite (Array, Class)
 Primitive data types
Data Type Description
byte 8-bit signed 2s complement integer ranging from -128 to 127 (inclusive)

short 16-bit signed 2s complement integer ranging from -32,768 to 32,767


(inclusive)

int 32-bit signed 2s complement integer ranging from -231 to 231-1


In Java 8: unsigned integer ranging from 0 to 232-1
long 64-bit 2s complement integer ranging from :
Signed : -263 to 263-1
Unsigned: 0 to 264-1 (in Java 8)
float is a single-precision 32-bit IEEE 754 floating point
Not to be used for currency representation- java.math.BigDecimal
double is a double-precision 64-bit IEEE 754 floating point
Not to be used for currency representation- java.math.BigDecimal
boolean true or false
char is a single 16-bit Unicode character, ranging from ‘\u0000’ to ‘\uffff’
 Default values
Data Type Default values
byte 0

short 0

int 0
long 0L
float 0.0f
double 0.0d

boolean false
char ‘\u000’
 Literals
Literals Default values

Integer literals • An integer number that can be assigned to integer


variable. Appending L or l to the number signifies the
long data type
• 3 number systems: decimal (0-9), binary (0 and 1)
and hexadecimal (0-9, A-F)
• Prefixes 0x and 0b indicates hexadecimal and binary
number respectively

Float-point A floating-point literal is of type float if it ends with the


literal letter F or f; otherwise its type is double and it can
optionally end with the letter D or d.

Character and Character literals are enclosed in single quotes


string literals String literals are enclosed in double quotes
 Variable Declaration

 [access type] datatype varName [=initial value];


e.g. int age;
float height = 1.92;
private int age;
private short age = 21;

 [access type] datatype list_of_varName;


e.g. public float vol, height, weight;
 Expression
 An Expression is a construct that consist of
variables, constants, operators or method
invocation which yield a single value

 Arithmetic expression
 Assignment expression

 Logical expression

 Relational expression
 Operators
 Arithmetic operators
 Assignment operators
 Logical operators
 Relational operators
 Unary operators
 Ternary operator
 Operators

 Arithmetic operators

Operator Description
+ Additive operator (also used for String
concatenation)
- Subtraction operator
* Multiplication operator
/ Division operator
% Remainder operator
 Operators
 Assignment operators
Operator Description
= x=y
+= x+=y
x=x+y
-= x-=y
x=x-y
*= x*=y
x=x*y
/= x/=y
x=x/y
%= x%=y
x=x%y
 Operators
 Relational operators

Operator Description
< Less than
<= Less than or equal to
> Greater than
>= Greater than or equal to
== Is equal to
!= Is not equal to
 Operators
 Logical operators

Operator Description
&& AND operator Returns true iff both operands are
true
|| Returns true if one or both operands are true
! Inverts the value of a Boolean
& Bitwise AND operator
| Bitwise OR operator
 Operators
 Unary operators

Operator Description
+ Indicates positive numbers
- Indicates a negative number or expression
++ Increment
-- Decrement
 Statement
A Statement is a complete program construct that causes
execution.

Itis simply an expression terminated with a semicolon:


Types:
 Null statement

 Simple statement

 Compound statement

 Control statement
 Statement
 Null
statement: is simply nothing terminated with a
semicolon i.e.,
;
 Simple statement; is single line statement e.g.

y = s + 15;
 Compound statement: is one or more simple statements

enclosed in a pair of curly braces. E.g.,


{ y = x+5;
x++; }
 Control flow statement

 Selection statements
 If
 If-else

 else if

 Switch

 Iteration statements (loops)


 while
 do-while

 for

 foreach
 Selection statement
 If statement
if (expr) stmt
e.g.
if(age >=18) status = “Adult”;

 If-else statement
If(expr) stmt_1
else stmt_2

e.g.
if(age>=18) status = “Adult”;

else status=“Teenager”;
 switch statement - byte, short, char, and int
Enum, String, Character, Byte, Short Integer,

switch(expr){
case val_1: stmt_1
break;
case val_2: stmt_2
break;
.
.
.
case val_n: stmt_n
break;
[default: default_stmt]
}
E.g.
int weekDay =5;
switch(weekDay){
case 1: System.out.println(“Sunday”);
break;
case 2: System.out.println(“Monday”);
break;
case 3: System.out.println(“Tuesday”);
break;
case 4: System.out.println(“Wednesday”);
break;
case 5: System.out.println(“Thursday”);
break;
case 6: System.out.println(“Friday”);
break;
case 7: System.out.println(“Saturday”);
break;
default: System.out.println(“Wrong day number”);
}
 Iteration statement
 while

while(expr)
stmt
e.g.

Short i=1;
While(i<6){
System.out.println(“This is iteration “ +i);
i=i+1;
}
 Iteration statement
 do - while
do{
stmts
}while(expr);

e.g.

int i=1;
do{
System.out.println(“This is iteration “, i);
i=i+1;
}While(i<6);
 Iteration statement
 For

for([initialization];[condition];[incr/decr]){ statement(s)
}
e.g.
for(short i=1;i<6;i++)
System.out.println(“This is iteration “, i);

 Enhancedfor each statement – designed for processing Collections and Arrays


for(type var: collection){
//statement using
}
 Other control statement
 break
int x=1;
while(x<10){
if(x==8)break;
System.out.println(“X = “,x);
x++;
}
 continue
int x=1;
while(x<10){
if(x==8){x++;continue;}
System.out.println(“X = “,x);
x++;
}
 Array
 Isa composite data type that group varibales of the same type under a common name
 Features of arrays:
 Components: the individual entities that make up the array. They are identified by using index. Java adopts zero
indexing
 Type: the data type of the components of the array
 Size: the number of components in the array
 Dimension: the number of different directions from which the array can be viewed and its components referenced

X
index 0 1 2 3 4 5 6 7 8 9
Each component of the array can be referenced through the index as follows: arrayName[n-1]
e.g. X[5]

12 5 34 66 98 65 99 72 45 87
 Array
 Linear Array
Array declaration
Datatype[] arrayName;
e.g.
int[] x //declare an array of integers
X null
Array allocation
arrayName = new Datatype[size];
e.g.
X = new int[10] //allocates memory for 10 int

X 0 1 2 3 4 5 6 7 8 9
 Array
 Linear Array
Initializing Array
Datatype[] arrayName = {val1, val2,…valN};
e.g.
int[] x = {23, 7, 90, 76, 12};

Example: Program to compute the sum of the array components


23 7 90 76 12
 Array
 Multi-dimensional Array e.g. matrice
 Requires more than one direction to reference its elements

Declaration
Datatype[][] arrayName; 34
e.g.
int[][] x Null
X
Array allocation
arrayName = new Datatype[size1][size2];
e.g.
X = new int[2][2]; X
 Array
 Multi-dimensional Array e.g. matrice

Initialization
double[][] y = {{12.0,7.1},{5.0,13}};

12.0 7.1
5.0 13
y

Example: Program to compute the sum of the components


in a 2-dimensional array
 Array
 Multi-dimensional Array
 Java treats multi-dimensional array as array of arrays
 Thus, a 2-dimensional array is a linear array in which each component is also a linear array
x

 Thus, irregular array can be created in Java


 Array
 Operations on Array
 Assignment operations
one array can be assigned to another of its type
e.g.: c = b
b

c
12 5 99 6 233
 arrayCopy(…) and copyOf(…)
arraycopy(…) is defined in the class System and has four parameters
43
System.arrayCopy(src, src_position, dest,8dest_position);
34 809 45

copyOf(…) is defined in the class Arrays, it returns array of the same type as its parameter. It as the forms:
Arrays.copyOf(src, len) or
Arrays.copyOfRange(src, src_position, src_end)
 Array
 Operations on Array
 Other operations on Arrays are
 sort( )
Arrays.sort(x);

 binarySearch(…)
Arrays.binarySearch(array, element);

 equals(…)
Arrays.equals(arrayA, arrayB);
 Packages
 Packages are directories (folders)
 Each class belongs to a package
 A class is added to a package by using the package statement:
package packageName;
 The package statement must precede every other statement in a class i.e. the package statement is the first line of statement in a class
 Where the statement is NOT specified, Java places the class in default package
 Classes in the same packages serve a similar purpose
 java.lang package which contains classes String, System, etc.
 java.io, java.net, java.text, java.awt, java.awt.color
 Visit: http://java.sun.com/javase/6/docs/api

 Classes in other packages need to be imported


 Using the import statement
import packageName. className
import packageName. *
 Classes in the same package do NOT need to use the
import statement

Why Packages?
 Combine/group class that perform similar functionality
 Separate classes with similar name
 Enhances collaborative software development
 Java Classes
Classes are constructs that define objects of the same type.
(Building plan of similar objects)
A Java class uses variables/constants to define data fields and
methods (member functions) to define behaviors.
 Java class definition

[accesstype] class className{


attribute_declaration

method_definition
}
where Access types: public, private and protected
 Attribute declaration:

[accesstype] datatype attribut_Name[= initVal];


e.g. private int age;

 Method definition:
[accesstype] returntype method_name([list of para]){
method_body
}

e.g.:
public String displayName(){
System.out.print(“Dr Amos Bajeh”);
}
 A Java class

public class Student {


private String name;
private String studentID;
private String surname; Attributes
private Course[] Courses;
private int level;

public void displayFullName(Course course) {


.
.
.
Methods }
public void setLevel() {
.
.
.
}
}
 Constructor
A class provides a special type of methods, known
as constructors, which are invoked to construct
objects from the class. They are basically invoked
to perform initialization actions
 Classes
class Circle {

double radius = 1.0; attribute

Circle() {
}
Constructors

Circle(double newRadius) {
radius = newRadius;
}

double computeArea() {
return radius * radius * 3.14159; Method
}
}
 Constructors, cont.
 A constructor with no parameters is referred to
as a default constructor
 Constructors must have the same name as the
class itself.
 Constructors have no return type—not even
void.
 Constructors are invoked using the new
operator when an object is created.
 Constructors play the role of initializing objects.
 Main method
 Java provides a main method from where
execution begins.
 The main method has the form:

public static void main(String[] arg){

//statements

}
 Objects Creation

 Object declaration:

[accesstype] class_name object_name;


e.g., public Circle myCircle;

 Object declaration/creation:

[accesstype] class_name object_name = new


class_name(list of args);
e.g.,
public Circle myCircle= new Circle();
public Circle myCircle = new Circle(radius);
 Accessing Objects

 Referencing the object’s data:


object_name.data
e.g., myCircle.radius

 Invoking the object’s method:


object_name.methodName(arguments)
e.g., myCircle.computeArea()
class Employee{
private String name;
private String id;
private int salary;

Employee() // default constructor. No argument list


{
name = “";
id = "";
salary = 0;

}
public Employee(String n, String i, int s) // non-default constr
{
name = n;
id = i;
salary = s;

}
void display()
{
System.out.println("\nEmploye Info ");
System.out.println("Name "+ name);
System.out.println("ID "+ id);
System.out.println("Salary "+ salary);
public static void main(String[ ] args){
Employee e1 = new Employee();
e1.display();

Employee e4 = new Employee("Ali","98745", 400);


e4.display();
}
}
public class Student {
private String name;
private String studentID;
private String surname;
private Course[] courses;
private int level;

public Student(String nameParam,String surnameParam) {


name=nameParam;
surname=surnameParam;
}

public displayInfo(){

public static void main(String[] args) {


Student s1 = new Student(“Onur”,”Saran”);
}
}
 Inheritance and Polymorphism
 Inheritance:
is the OOP feature in which a class (object) can possess the attributes and
methods of another class (object)
 Subclass: a class that is derived from another class
 also known as derived class, extended class, or child class.
 Superclass : the class from which the subclass is derived
 also known as base class or a parent class
 Inthe absence of any other explicit superclass, every class is implicitly a
subclass of Object.
 Inheritance
 Inheritance definition: the keyword extends is used for inheritance definition. The syntax is
as follows:

[accesstype] class subclass extends superclass {


attribute_declaration

method_definition
}

Person

Employee
 Example:
public class Person {
String name, addresss, sex;
int age;
float weight, height;
Person(String n, String a, String s,
int ag,float w, float h){
name=n; address=a; sex=s;
age=ag;weight=w;height=h;
}
public displayDetail(){
System.out.println(“NAME: “+name);
System.out.println(“ADDRESS: “+address);
System.out.println(“SEX: “+sex);
System.out.println(“AGE: “+age);
System.out.println(“WEIGHT: “+ weight);
}
}
 Example:
public class Employee extends Person {
int staffNumber;
String dept;
public displayDetail(){
System.out.println(“NAME: “+name);
System.out.println(“ADDRESS: “+address);
System.out.println(“SEX: “+sex);
System.out.println(“AGE: “+age);
System.out.println(“WEIGHT: “+ weight);
System.out.println(“Number: “+staffNumber);
System.out.println(“DEPT: “+ dept);
}
}
 Points to note about inheritance

 The inherited attributes/methods can be used directly, just like any other fields.
 You can declare a attribute/method in the subclass with the same name as the one in the superclass,
thus hiding it .
 You can declare new attributes/methods in the subclass that are not in the superclass.
 You can write a new instance method in the subclass that has the same signature as the one in the superclass,
thus overriding it –method overriding
 You can write a new static method in the subclass that has the same signature as the one in the superclass,
thus hiding it.
 You can write a subclass constructor that invokes the constructor of the superclass, either implicitly or by using
the keyword super.
 A subclass does not inherit the private members of its parent class.
 Inheritance and Polymorphism
 Polymorphism: is the OOP feature in which two or more objects response in different forms to the same
message

 InJava, it can be implemented in two ways:


 Using Inheritance

 Using Interface (to be discussed later)

 Using Inheritance
 Since methods can be inherited from a class and

 More than one class can inherit from the same class

 Inheriting classes can provide unique definitions for the same method inherited from a class

 Since objects of subclasses are also objects of the super class type
Person

Employee Student

Why do we need Inheritance and Polymorphism?


 Interface
 Interface: is the a java type that consist of abstract methods and probably constants which are static type.

 Abstract methods are methods that do not have body, just the return type and signature

 The following is a syntax format for java interface definition

[accesstype] interface interfaceName{


constant_declaration

method_header
}
 Interface implementation
 Interfacesis implemented by classes
 A class implementing an interface must provide definition for all the abstract methods in the interface
 The following is a syntax format for java interface implementation:

[accesstype] class clasName implements listOfInt{


attribute_declaration

method_definition
}
 Interface implementation

<<Planes>>

 Why the need for interface?


abstraction is the process of hiding certain details and showing only essential information to the user.

Rectangle Triangle
 Interface implementation

 Interface methods do not have definitions


 interfaces cannot be used to create objects
 Interface methods do not have a body - the body is provided by the class that implements it
 All the methods of an interface must be defined when implementing it
 Interface methods are by default abstract and public
 Interface attributes are by default public, static and final
 Interface must not have constructors
Exception
Definition:

An exception is an event, which occurs during the


execution of a program, that disrupts the normal
flow of the program's instructions. (Oracle Java
Doc.)

•Such event could be caused by an error such as division by


zero, floating-point overflow, subscript out of range, invalid input
and end-of-file encounter
Exception
• The program needs to handle exceptions when it
occurs otherwise the program end abruptly.

• When an error occurs within a method, the method


creates an object, called an exception object and
hands it off to the runtime system

• The object contains information about the error,


including its type and the state of the program when
the error occurred

• Creating an exception object and handing it to the


runtime system is called throwing an exception
Exception
Catch or Specify requirement

all code that might throw an exception must be


enclosed in either of the following

• The try block that catches and handles


the exception

• A method that throws the exception


Exception
Java exception handling mechanism

Java handle exception by using the try-catch-finally


blocks:

try{
//the code to watch for exception
}catch(Exception e){
//code to handle the exception
}finally{
//executes however
}
Exception
Note the following about the try block
• It can be nested

• There can be several catch block in a try block

• When an exception is thrown, the parameters of the catch


block are used to select which handler to use for the
exception

• If the inner try block has no matching catch, the outer try
block is searched for a match

• If no match is found, the java default exception handler is


invoked to handle the exception. The java exception
handler is defined to display the exception and terminate
the program
Exception
• The throw statement
• This statement is explicitly used by programmers to

generate exception within try blocks

• It takes the form:


throw obj;
where obj is an instance of any subclass of the Throwable
class

see demo
Exception
• The throws clause
• This clause is used to indicate that a method can throw
some exceptions which the method did not provide
handler for. Thus, the user of the method should provide a
way of handling the exception(s)

• The format for defining such method is as follows:

returntype methodname(paraList) throws list_of_exceptions{


// method body
}
Exception
• After a method throws an exception, the runtime system attempts to do
“something” to handle it. The set of possible "somethings" to handle the
exception is the ordered list of methods that had been called to get to the
method where the error occurred.
• The list of methods is known as the call stack

• Call stack Searching the call stack for exception handler


Exception
• User-defined Exception
• A programer can defined his/her own exception class
apart from the ones defined by Java.

• The user-defined exception must be an extension of the


Throwable class or its descendant, most expecially the
Exception class

class myException extends Exception{


// method body
}
Exception
Readings:

https://docs.oracle.com/javase/tutorial/essent
ial/exceptions/definition.html
Requirements Engineering
Object Modeling:
• Is the identification and representation of the objects, the
operations on the objects, and relationships between the
objects

• Classes: objects with common attributes and behaviors

• Identifying [Analysis] classes, attributes and operations:


• performing grammatical parse on use cases/ user
stories developed for the system to be built

• Noun/noun phrase indicates class

• Verb indicate operations


Requirements Engineering
Potential Classes show up as:
• External entities (e.g., other systems, devices, people) that
produce or consume information

• Things (e.g., reports, displays, letters, signals) that are part of


the information domain for the problem.

• Roles (e.g., manager, engineer, salesperson) played by


people who interact with the system.

• Organizational units (e.g., division, group, team) that are


relevant to an application.
Requirements Engineering
Use case example:
The SafeHome security function enables the homeowner to configure the
security system when it is installed, monitors all sensors connected to the
security system, and interacts with the homeowner through the Internet, a PC,
or a control panel.
During installation, the SafeHome PC is used to program and configure the
system. Each sensor is assigned a number and type, a master password is
programmed for arming and disarming the system, and telephone number(s)
are input for dialing when a sensor event occurs.
When a sensor event is recognized, the software invokes an audible alarm
attached to the system. After a delay time that is specified by the homeowner
during system configuration activities, the software dials a telephone number of
a monitoring service, provides information about the location, reporting the
nature of the event that has been detected. The telephone number will be
redialed every 20 seconds until telephone connection is obtained.
The homeowner receives security information via a control panel, the PC, or a
browser, collectively called an interface. The interface displays prompting
messages and system status information on the control panel, the PC ,or the
browser window. Homeowner interaction takes the following form . . .
Requirements Engineering
Use case example:
Potential classes General classification
homeowner role or external entity
sensor external entity
control panel external entity
installation occurrence
system thing
number, type Not an object, Attributes of sensor
master password thing
telephone number thing
sensor event occurrence
audible alarm Thing or external entity
monitoring service Organisation or external entity
Requirements Engineering
6 Selection Characteristics :
Characteristics description
1. Retain information The potential class will be useful during analysis only if
information about it must be remembered so that the
system can function
2. Needed service The potential class must have a set of identifiable
operations that can change the value of its attributes in
some way
3. Multiple attributes Classes with major information; a class with a single
attribute may probably be better represented as an
attribute of another class
4. Common attributes A set of attributes can be defined for the potential class
5. Common operations A set of operations can be defined for the potential class
6. Essential requirement External entities that appear in the problem space and
produce or consume information essential to the operation
of any solution for the system will almost always be defined
as classes in the requirements model
Requirements Engineering
Applying the 6 selection characteristics:
Potential classes General classification
homeowner Rejected: 1 and 2 fail, even thou 6 applies
sensor Accepted: all apply
control panel Accepted : all apply
installation Rejected:
system Accepted: all apply
number, type Rejected: 3 fails, attribute of sensor
master password Rejected: 3 fails
telephone number Rejected: 3 fails
sensor event Accepted : all apply
audible alarm Accepted : 2, 3, 4, 5, 6 apply
monitoring service Rejected: 1 and 2 fail, even thou 6 applies
Requirements Engineering
Categories of class:

• Entity classes (a.k.a. model or business classes)

• Boundary classes: creates interfaces e.g. interactive


screens and printed reports

• Controller classes: manage a “unit of work” from start to


finish
Requirements Engineering
Defining the attributes of class:
• The data items that describes the class in the problem context
• Thus, attempt to answer the question:

What data items(composite and/or elementary) fully define


this class in the context of the problem at hand?”

e.g.
• Sensor: roomLocation, active

• System: systemID, phoneNumber, masterPassword,


numberOfTries, etc.
Requirements Engineering
Defining the operations of class:
Four broad categories of operations:

• Operations that manipulate data (e.g., adding, deleting,


reformatting, selecting)

• Operations that perform computation

• Operations that inquire about the state of an object, and

• Operations that monitor an object for the occurrence of a


controlling event
Requirements Engineering
Defining the operations of class:
Example:
from the use case narrative, the sensor is assigned a number
and type or a master password is programmed for arming
and disarming the system.” Thus:

• an assign() operation is relevant for the Sensor class.

• a program() operation will be applied to the System class.

• The system can be armed- arm() – and disarmed -


disarm() -are operations that apply to System class.
Class Diagram Description
 Class Diagram shows a collection of classes,
interfaces, associations, collaborations and
constraints. It is also known as a structural diagram

 It provides a conceptual model of the system in


terms of entities and there relationships

 A collection of class diagrams represent the whole


system.
Purpose of Class Diagram
 The main purpose of a class diagram is to
model, analyse and design the static view of an
application.

 It is used to describe responsibilities of the


components a system.
How to draw a class diagram
 A class is represented with a box which has three
compartments
 Name: the top compartment contains the name of the class. It
is printed in bold and the first letter is capitalized

 Attributes: the middle compartment contains the attributes of


the class. They are left aligned and the first letter is lower case

 Operations: The bottom part gives the methods or


operations the class can undertake. They are also left aligned
and the first letter is lower case.
UML Class Diagram

Circle Cars
Class name

radius: float model: integer


color: String
attributes

Circle( ) Cars( )
computeArea( ) accelerate( )
decelerate( )
methods
break( )

Excercise1: think of two different classes of


objects and draw class icons for them, stating
their attributes and methods
Requirements Engineering
The class representation:

System

systemID
phoneNumber
masterPassword
numberOfTries

program()
arm()
disarm()
display()
dial()
Modifiers:
+ public
- private
# protected
Note the following:
 The name of the class diagram should be meaningful to describe
the aspect of the system.
 Each element and their relationships should be identified in
advance.
 Responsibility (attributes and methods) of each class should be
clearly identified.
 For each class minimum number of properties should be
specified. Because unnecessary properties will make the
diagram complicated.
 Use notes whenever required to describe some aspect of the
diagram. Because at the end of the drawing it should be
understandable to the developer/coder.
 Finally, before making the final version, the diagram should be
drawn on plain paper and rework as many times as possible to
make it correct.
Association Association Multiplicity
 Represents relationships Indicator
between instances of
classes.
 An association is a link
connecting two classes.
 Bidirectional Association
denoted by e.g.
flight and plane
 Unidirectional Assocation
denoted by
e.g. order and item
Example of Class Diagram

You might also like