object oriented methodology · cobol fortran lips ... vb.net c# python. oo terms and concepts o...
Post on 15-Jun-2020
7 Views
Preview:
TRANSCRIPT
Object Oriented Methodology
เสถยร หนตาคณะเทคโนโลยสารสนเทศและการสอสารมหาวทยาลยพะเยา
Software development and design
◼ Software
❑ ชดค าสงหรอโปรแกรมทใชควบคมการท างานของเครองคอมพวเตอรทเขยนขนดวยภาษาคอมพวเตอร
❑ สรางขนเพอแกปญหาของผใชและท างานตามทผใชตองการไดอยางถกตอง
Software Development
Software Development Life Cycle
Software Analysis and Design
◼ Structured Analysis and Design
◼ Object Oriented Analysis and Design
Structured Analysis and Design
◼ Data Oriented
❑ Data Flow Diagrams (DFD)
❑ Entity Relationship Diagrams (ERD)
◼ Action Oriented
❑ Finite State Machine (FSM)
DFD Level 0
DFD Level 1
DFD Level 3
DFD
ER Diagram
Object-Oriented Analysis
◼ Builds a real-world model from requirements
❑ client interviews
❑ domain knowledge
❑ real-world experience
◼ The model addresses three aspects of objects
❑ class structure and relationships
❑ sequencing of interactions and events
❑ data transformations and computations
Models of Object-Oriented Analysis
◼ Class Model
❑ static structure
❑ what objects are in the system?
❑ how are they related?
◼ Dynamic Model
❑ behavioral aspects
❑ what events occur in the system
❑ when do they occur and in what
order?
◼ Functional Model
❑ data transformations
❑ “what” does the system do
◼ Data-Oriented
◼ Action-Oriented
◼ Both Data and Actions
Object Oriented Analysis and Design
◼ The Unified Modeling Language (UML)
ตวอยาง
Use-case diagram Class diagram
UML DiagramsStructural
: element of spec. irrespective of time
◼ Class
◼ Component
◼ Deployment
◼ Object
◼ Composite structure
◼ Package
Behavioral: behavioral features of a system / business process
◼ Activity
◼ State machine
◼ Use case
◼ Interaction
Interaction: emphasize object interaction
• Communication (collaboration)
• Sequence
• Interaction overview
• Timing
Structured analysis and design
Object oriented analysis and design
Functions
◼ What we call them:
functions, methods, modules
◼ Functions are a core construct in OO and
non-OO programs
◼ Principals of good functions apply in either
language
❑ But less of a problem in OO – can you think why?
Functions
◼ Functional decomposition❑ แยกปญหาใหเปนสวนยอย
❑ ใช function แกปญหาทละสวน❑ มลกษณะเปนล าดบชน
◼ Problems
❑ การควบคมและการประสานงาน รวมอยท Main method
❑ การเปลยนแปลงท าใหเกดผลกระทบมาก
Functions
◼ Functions, Methods, Modules
◼ Cohesion
◼ Coupling
Cohesion and Coupling
◼ Cohesion (การเกาะยด)❑ การเกาะยด คอระดบของความสมพนธภายใน module
❑ หาก module มการเกาะยดสง แสดงวาสามารถท างานดวยตวของมนเองระดบหนง และมการเรยกใชหรอผกยดกบโปรแกรมตาง module นอย
◼ Coupling (การปฏสมพนธ)❑ การตดตอสงขอมลระหวาง module
❑ ถาระบบใดมปฏสมพนธระหวาง module มาก การยดเกาะภายในจะมโอกาสลดนอยลง
Goal
◼ Flexibility, independence of modules
◼ Looser connections, less brittle system
◼ Reusability
Loosely-coupled modules, each highly
cohesive
Object Oriented Programming
❑ Object
❑ Attributes, Methods and Events.
❑ Inheritance
❑ Encapsulation
❑ Polymorphism
Programming Languages
◼ ภาษาคอมพวเตอรใชในการสรางซอฟแวร◼ แบงเปน 3 กลมหลก ๆ
❑ Machine languages
❑ Assembly languages
❑ High-Level languages
Machine Languages
◼ เปนเลขฐานสอง ประกอบดวย 0 และ 1◼ มความยากในการเขยนโปรแกรมเนองจาก
❑ เปนภาษาทมนษยเขาใจไดยาก❑ ความผดพลาดเพอ 1 จดกท าใหโปรแกรมลมเหลวได❑ ตวอยาง
◼ 1110100010101 111010101110 10111010110100 1010001110111
Assembly Languages
◼ เกดจากการออกแบบตวอกษรภาษาองกฤษใหแทนค าสงรหสเลขฐานสองเรยกวา รหส mnemonic
◼ คอมพวเตอรตองแปลเปนภาษาเครองกอนประมวลผล◼ ตวอยาง
❑ ADD 1001010, 1011010
High-Level Languages
◼ เปนภาษาทท าใหการเขยนโปรแกรมงายขน◼ ใกลเคยงกบภาษามนษย◼ แบงเปน สองกลมหลก
❑ Procedural (Structural) languages
❑ Object-Oriented Languages
Procedural Languages
◼ เปนภาษาระดบสง ทมลกษณะเปนค าสงเรยงล าดบเปนขนตอน และเปนโครงสราง
◼ ตวอยาง❑ C
❑ COBOL
❑ Fortran
❑ LIPS
❑ Perl
Object-Oriented Languages
◼ ใหความสนใจท modeling data ไมใชโครงสราง◼ เขยนโปรแกรมโดยใชแบบแปลนของแบบจ าลอง Classes
◼ ตวอยาง❑ C++
❑ Java
❑ VB.NET
❑ C#
❑ Python
OO Terms and Conceptso Object and Classo Inheritance, Encapsulation and
Polymorphismo Relationship and Interaction between
classes
OO Analysis and Designo Object Modeling with UMLo UML Diagramso Tools
Mapping UML model into OO Programming Languageso Java Language
วตถ
• วตถ (Object)เปน กลมหรอชด (collection) ของสงตอไปน• แอททรบวต (Attribute) ของวตถจะบอกถงขอมล (Data) คณลกษณะเฉพาะหรอ สถานะของวตถ • เมทธอด (Method) จะบอกถงหนาท (functionality) หรอ พฤตกรรม (behavior) ตางๆของวตถนนๆ
• โดยม แอสโซซเอชน (Association) อนไดแก สงทบอกถงความสมพนธ (Relationship) ของวตถนน กบวตถอนๆ รวมทงปฏสมพนธ (Interactions) ระหวางวตถกบวตถอนๆ
การสรางแบบจ าลองของวตถ
• ระบ ขอบเขตของปญหา (Problem Domain) เพอสรางแบบจ าลองวตถ(Modeling Objects)
o เปนการก าหนดขอบเขตของสงทเราจะพจารณาใหเปนวตถ (Object) o เราไมสามารถสนใจทกๆ วตถ (Object) ในโลกของความเปนจรง ในเวลาเดยวกนไดo เชนเดยวกบทเราไมสามารถสนใจทกความสมพนธ และ กจกรรม ทกความสมพนธ และทกกจกรรมทเกดขนในโลกของความเปนจรงไดเชนกน
Objects = Attributes, Methods,
AssociationsAttributes
AgeGenderName….
AssociationsmyLeftArmmyLeftLegmyRightArm....
Methods/OperationsJump..Talk...Dance
Ask FriendJumpWalkJumpShake myHeadShake myBody
Tim
Objects = Attributes, Methods,
AssociationsAttributes
ModelCompanyColor….
AssociationsBrakeLeftFrontWheelGear....
Methods/OperationsStart..Go...Stop..
Go ForwardGo BakcwardTurn LeftTurn RightApply BrakeChange Gear….
รถยนต Toyota สแดง
• ก าหนดคณลกษณะ (Attribute) ใหกบวตถo วตถ Tim มคณลกษณะส าคญคอ อาย (25 ป) เพศ (ชาย) ชอ (Tim) o วตถ รถยนตคนหนง เปน รถ สแดง ยหอ Toyota
• ก าหนดพฤตกรรม/วธการกระท า (Method) ใหกบวตถo วตถ Tim สามารถ เดน ยน นง และนอน ไดo วตถ รถยนตคนหนง สามารถ วง เลยวซาย และเลยวขวาได
• ก าหนดความสมพนธ/ปฏสมพนธกบวตถอน (Association)o วตถ Tim สามารถสรางกจกรรม ใหวตถ รถ เกดการเปลยนแปลงสถานะได เชน การขบรถ
Objects Abstraction
• วตถทม Attribute, Method และ Association ของวตถคลายๆ กนจะถกจดอยในกลมหรอ คลาส (Class) เดยวกน
Group of Objects
• คา Attribute, Method และ Association ของวตถ จะถกก าหนดไวใน “คลาส” (Class)• คลาส (Class)
o เปนสงทน าเสนอ Abstract Data Types (ADTs) ของวตถ (Object) ทเราตองการจ าลองo ก าหนดรายละเอยดเกยวกบ Attribute, Method และAssociation ของวตถ (Object)o เปนพมพเขยว (Blueprint) ของวตถ (Object)
Defining Class
• คลาส (Class) เปนพมพเขยว (Blueprint) ของวตถ (Object)o ไมสามารถน ามาใชไดโดยตรง o ก าหนดคณลกษณะรวมกนในรปของ Attributeo ก าหนดวธการกระท า/พฤตกรรม รวมกนของวตถ ในรปของ Method o ก าหนดความสมพนธ /ปฏสมพนธกบวตถอนในรปของ Association
• เรยกไดวา วตถ (Object) เปนสงทสรางขน หรอเปน อนแสตนซ (Instance) ของคลาส (Class)
Class & Instance
Class & Object
Class
PERSON
Age
Gender
Name
myArms
myLegs
Jump()
Walk()
Talk()
Dance()
ShakeMyArms()
Object “Tim”
Age = 25
Gender = Male
Name = Tim
myArms = Arms
myLegs = Legs
can Jump
can Walk
can Talk
can Dance
can ShakeMyArms
Class & Object
Class
PERSON
Age
Gender
Name
myArms
myLegs
Jump()
Walk()
Talk()
Dance()
ShakeMyArms()Object “Don”
Age = 25
Gender = Male
Name = Don
myArms = Arms
myLegs = Legs
can Jump
can Walk
can Talk
can Dance
can ShakeMyArms
Class & Object
Class คอ ตนแบบขอมลทมไวเพอสราง object ทมโครงสรางพนฐานพฤตกรรมเดยวกน ในแนวคดเชงวตถกอนทสราง object จะตองสราง class ขนมากอน
Object ทกตวจะตองอยใน class ซง class กบobject เปนสงทคกนเสมอ สามารถทราบรายละเอยดและคณสมบต ของ Object ไดดวยการดท Class
Class
Class จะประกอบดวยชอ Class, Attribute และ Method ตาง ๆ ซงเปนตวอธบายรายละเอยด และหนาทตาง ๆ โดยแสดงในลกษณะ diagram ดงน
Name
Attributes
Method
Class
ตวอยาง Class ของ StudentStudent
{abstract}
StudentIDNumber
FirstName
LastName
Address
City
State
RegisterForCourse
DropCourse
ChangeAddress
Class
ใน C++
การสราง Class ท าไดโดยการประกาศ class ซงมสวนประกอบดงน class CRectangle {
int x, y;
public:
void set_values (int,int);
int area (void);
} rect;
attribute
Method
ชอ object สรางจากคลาส
ชอ Class
Class // classes example
#include <iostream>
using namespace std;
class CRectangle {
int x, y;
public: void set_values (int,int); int area () {return (x*y);} };
void CRectangle::set_values (int a, int b) { x = a;
y = b;
}
int main () { CRectangle rect;
rect.set_values (3,4); cout << "area: " << rect.area(); return 0;
}
Method
รายละเอยด Method น ามาเขยนดานลาง Class
การสราง object จาก class
การเรยกใช method
Message passing
◼ การสง Message ไปยงวตถใดๆ แลววตถนนกระท าการอยางใดอยางหนง o เปนการเรยก Method ทถกก าหนดไวในวตถนนมาท างานo แตละวตถ ตองรบผดชอบ พฤตกรรมของตนเอง โดยผานการ
เรยกใช Method
Tim
ถาวตถ Tim ตองการขบรถ aCar
aCaraCar.GoForward(100)aCar.goBackward()
aCar.TurnLeft()
aCar.TurnRight()
aCar.ApplyBrake()
Example of Message Passing
Object-Oriented Software
m1
m2
m4m3
m5
Software
Environment
Characteristics of an Object
◼ Identity
◼ Information Hiding
◼ Encapsulation
◼ Inheritance
◼ Polymorphism
Identity
วตถ (Object) จะตองมลกษณะเฉพาะประจ าตว (Identity)o วตถใดๆ สามารถมคณลกษณะ (Attribute) เหมอนๆ กนได เชน วตถ
“Tim” และ“Don” เปนเพศชาย และอาย 25 ป เหมอนกนo วตถใดๆ สามารถมพฤตกรรม (Behavior/Method) เหมอนๆ กน
ได เชน วตถ“Tim” และ“Don” สามารถกน เดน นอน นง ไดเหมอนกน
o วตถใดๆ สามารถความสมพนธเกยวของ (Association) กบวตถอนๆเหมอนๆ กนได เชน วตถ“Tim” และ“Don” ประกอบดวย 2 แขนและ 2 ขา เหมอนๆ กน
o วตถ “Tim” และ “Don” สรางจากคลาส (Class) เดยวกนคอ “Person”
แตเราถอวา วตถ“Tim” และวตถ “Don” เปนคนละวตถกน
Encapsulation
◼ พจารณาวตถ (Object) ไดเสมอน กลองด า (Black Box)
o วตถใด ตอง “ร” วธหรอขนตอนการท างานภายใน (Method) ของตนเอง
o วตถอน ไมจ าเปนตองรวาวธ หรอขนตอนการท างานภายในเปนอยางไรo วตถอนตองการเรยกใช Method ของวตถนได โดยสง Message มา
โดยท Message จะตองอยในรปแบบทตกลงกนไวกอน
black box
Object
IncomingMessage Outgoing Message
Information Hiding
◼ พจารณาวตถ (Object)
o สามารถก าหนดขอบเขตการเขาถง Attribute และ Method
o ก าหนดวาใครสามารถเหนหรอใช Attribute และ Method ของวตถนนไดบาง
anObject
talk()walk()jump()
NameAge
ObjectDiagram A.
anObject
talk()walk()
jump()
NameAge
Object Diagram B.
anObject
talk()walk()
Jump()
NameAge
Object Diagram C.
Information Hiding and Encapsulation
• ค าถาม: จะค านวณคา “Age” จาก PERSON ไดอยางไร?
o เกบคา วน-เดอน-ปเกด ไว แลวค านวณคา “Age” เมอม การรองขอo เกบคาอายปจจบน (current age) และupdate ทกๆ ป
• ค าตอบ: แลวแตวตถนนจะใชวธไหนตามความถกตองและเหมาะสม โดยก าหนดท Method “getAge()”
PERSON
Age
Gender
Name
myArms
myLegs
Jump()
Walk()
Talk()
Dance()
ShakeMyArms()
getAge()
Advantages of Information Hiding
and Encapsulation◼ Maintainability
o เปนการพจารณาโครงสรางซอฟแวรในระดบนามธรรม (Abstraction) หรอในระดบสง (High-Level) โดยไมค านงถงรายละเอยด วธการ หรอภาษาทจะน าไปพฒนา (Implementation)
◼ Flexibility
o ท าใหการพฒนาซอฟแวรเชงวตถมความยดหยน (Flexibility) สามารถเปลยนแปลงไดงาย (Ease of Change)
o ระบบ Software ใดๆ สามารถปฏบตงานรวมกนไดอยางสะดวก และมประสทธภาพ เนองจากไมจ าเปนตอง “ร” รายละเอยดการท างานภายในของระบบ
JAVA
การแสดงผลเบองตน
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello World!");
}
}
◼ println เปน static member
method ของ class System
การแสดงผล
Public class Simple
{ pubic static void main(String[] args)
{ System.out.print(“Hello word”);
}
}
System class
Out object
Print method
Method mainชอ class
Method รบขอมล
น าเขาคลาส Scanner เพอเรยกใช method ส าหรบรบขอมล
import java.util.Scanner;
สราง object ชอ input
Scanner input = new Scanner(System.in);
เรยกใช method จาก object input
int x = input.nextInt();
ทดสอบการแสดงผล
System.out.print(“input is ”+x);
package javaapplication1;
import java.util.Scanner;
public class JavaApplication1 {
public static void main(String[] args) {
int x;
Scanner input = new
Scanner(System.in);
x = input.nextInt();
System.out.println("input is "+x);
}
}
Comments are almost like C++
◼ /* This kind of comment can span multiple lines
◼ ใชไดกบหลายบรรทด */
◼ // This kind is to the end of the line ใชกบบรรทดเดยว
◼ /**
* This kind of comment is a special
* ‘javadoc’ style comment
*/
ชนดของขอมล
Primitive data types
◼ Main data types are int, double, boolean, char
◼ Also have byte, short, long, float
◼ boolean has values true and false
◼ Declarations look like C, for example,
❑ double x, y;
❑ int count = 0;
Expressions
◼ Assignment statements mostly look like those in C; you can use =, +=, *= etc.
◼ Arithmetic uses the familiar + - * / %◼ Java also has ++ and --
◼ Java has Boolean operators && || !◼ Java has comparisons < <= == != >= >◼ Java does not have pointers or pointer
arithmetic
Operator
◼ Arithmetic Operator
◼ Relational Operator
◼ Logical Operator
◼ Bitwise Operator
Operator
Arithmetic operators
Shorthand assignment operator
>, >=, <, <=,==, !=
&&, ||, !
Relational Operator
Logical Operator
Bitwise Operator
~,&,|,^,>>,>>>,<<
Operator
PRECEDENCE LEVEL ASSOCIATIVITY Operator
1 R to L ++, --, +, -, ~, !, (data type)
2 L to R *, /, %
3 L to R +, -
4 L to R <<, >>, >>>
5 L to R <, >, <=, >=, instanceof
6 L to R ==, !=
7 L to R &
8 L to R ^
9 L to R |
10 L to R &&
11 L to R ||
12 R to L ?:
13 R to L =, +=, -=, *=, /=, %=, etc.
Control statements
◼ if (x < y) smaller = x;
◼ if (x < y){ smaller=x;sum += x;}
else { smaller = y; sum += y; }
◼ while (x < y) { y = y - x; }
◼ do { y = y - x; } while (x < y)
◼ for (int i = 0; i < max; i++)
sum += i;
conditions must be Boolean !
Control statements II
◼ Java also introduces the trystatement, about which more later
switch (n + 1) {
case 0: m = n - 1; break;
case 1: m = n + 1;
case 3: m = m * n; break;
default: m = -n; break;
}
Java กบ C
◼ In C, almost everything is in functions
◼ In Java, almost everything is in classes
◼ There is often only one class per file
◼ There must be only one public class per file
◼ The file name must be the same as the
name of that public class, but with a .javaextension
Java program layout
◼ A typical Java file looks like:
import java.awt.*;
import java.util.*;
public class Hello {
// object definitions go here
. . .
}
ชอ File ตองตงชอเปน Hello.java
Class
◼ ภาษาคอมพวเตอรยคแรก ๆ จะมแค arrays
❑ ทก ๆ คาใน arrays ตองเปนชนดเดยวกน
◼ ภาษายคตอมาจะม structures (structs)
❑ สามารถมขอมลตางชนดกน อยเปนกลมภายใน structure
◼ Abstract Data Types (ADTs)❑ รวมวธการหรอ function กบขอมลไวดวยกน
struct Books {
char title[50];
char author[50];
char subject[100];
int book_id;} book;
Class
◼ A class consists of
❑ a collection of attributes, or variables (คลายกบstructs ในภาษา C)
❑ ม methods ทสามารถจดการกบ attributes
◼ สามารถ น ามาสรางเปน object (can be instantiated)
กฎการตงชอ Class
ธรรมเนยมการตงชอ Class
❑ อกษรตวแรกของชอควรเปนตวอกษรใหญ (capital
letter)
❑ อกษรตวแรกตวแปรอนใหเปนตวอกษรเลก
❑ ไมใช Underscores ในชอ Class
- ชอตองประกอบดวย ตวอกษรตวเลข $ หรอ _ - ชอหามขนตนดวยตวเลข- สามารถตงชอยาว ๆ ได- ชอตวอกษรตวเลกกบตวใหญถอวาตางกน- ตองไมซ ากบค าสงวนของภาษาจาวา- ตองไมซ ากบชออนของโปรแกรมทใชมากอน
An example of a class
class Person {
String name;
int age;
void showage ( ) {
System.out.println (name + ' is now '
+ age);
}
}
Another example of a class
class Driver extends Person {
long driversLicenseNumber;
Date expirationDate;
}
Creating and using an object
◼ Person john;
john = new Person ( );
john.name = "John Smith";
john.age = 37;
◼ Person mary = new Person ( );
mary.name = "Mary Brown";
mary.age = 33;
mary.birthday ( );
An array is an object
◼ Person mary = new Person
( );
◼ int myArray[ ] = new
int[5];
❑ or:
◼ int myArray[ ] = {1, 4,
9, 16, 25};
◼ String languages [ ] =
{"Prolog", "Java"};
array ใน JAVA เปนการใช object แบบหนง
78
Classes
◼ A class is a collection of attributes (data) and
methods (procedure or function) that operate
on that data.
Circle
centre
radius
circumference()
area()
79
Classes
◼ A class is a collection of attributes (data) and methods (procedure or function) that operate on that data.
◼ The basic syntax for a class definition:
class ClassName [extends
SuperClassName]
{
[fields declaration]
[methods declaration]
}
80
Class Circle
◼ Add attributes
◼ The attributes (data) เรยกอกอยางหนงวา instance variables
public class Circle {
public double x, y; // centre coordinate
public double r; // radius of the circle
}
81
Methods
◼ A class with only attribute(data fields) has no life. Objects created
by such a class cannot respond to any messages.
◼ Methods จะประกาศหลงจาก attributes.
◼ The general form of a method declaration is:
type MethodName (parameter-list)
{
Method-body;
}
Method
◼ Static Method
◼ Instance Method
◼ Overloading Method
83
Class Circle
public class Circle {
public double x, y; // centre of the circle
public double r; // radius of circle
//Methods to return circumference and area
public double circumference() {
return 2*3.14*r;
}
public double area() {
return 3.14 * r * r;
}
}
Method Body
84
Data Abstraction
◼ Declare the Circle class, have created a new
data type – Data Abstraction
◼ สามารถประกาศ object ไดดงน
Circle aCircle;
Circle bCircle;
85
Class of Circle
◼ aCircle, bCircle simply refers to a Circle object, not an object itself.
◼ aCircle และ bCircle ชไปยง วตถชนด Circle
aCircle
Points to nothing (Null Reference)
bCircle
Points to nothing (Null Reference)
null null
86
Creating objects of a class
◼ Objects are created dynamically using the
new keyword.
◼ ใช new ในการสรางวตถโดยจะม aCircle และ bCircle ชไปยงวตถนน
◼ aCircle and bCircle refer to Circle objectsbCircle = new Circle() ;aCircle = new Circle() ;
87
Creating objects of a class
aCircle = new Circle();
bCircle = new Circle() ;
bCircle = aCircle;
88
Creating objects of a class
aCircle = new Circle();
bCircle = new Circle() ;
bCircle = aCircle;
x
aCircle
y
bCircle
Before Assignment
x
aCircle
y
bCircle
Before Assignment
//bCircle ถกยายไปช วตถ ท aCircle ชอย
89
Automatic garbage collection
◼ The object does not have a reference and cannot be used in future.
◼ วตถท bCircle ชอยเดมจะไมถกใชอกในอนาคต เพราะไมมตวชหรออางถงอกตอไป
◼ The object becomes a candidate for automatic garbage collection.
◼ Java automatically collects garbage periodically and releases the memory used to be used in the future.
90
การเขาถง attribute
◼ Similar to C syntax for accessing data
defined in a structure.
◼ ใช . ในการอางถง attribute ภายใน object
Circle aCircle = new Circle();
aCircle.x = 2.0 // initialize centre and radius
aCircle.y = 2.0
aCircle.r = 1.0
เชนObjectName.VariableName
ObjectName.MethodName(parameter-list)
91
Executing Methods in Object/Circle
◼ Using Object Methods:
◼ ใช . เพอเรยกใช method ของ object
Circle aCircle = new Circle();
double area;
aCircle.r = 1.0;
area = aCircle.area();
sent ‘message’ to aCircle
92
Using Circle Class// Circle.java: Contains both Circle class and its user class
//Add Circle class code here
class MyMain
{
public static void main(String args[])
{
Circle aCircle; // creating reference
aCircle = new Circle(); // creating object
aCircle.x = 10; // assigning value to data field
aCircle.y = 20;
aCircle.r = 5;
double area = aCircle.area();
double circumf = aCircle.circumference();
System.out.println("Radius="+aCircle.r+" Area="+area);
System.out.println("Radius="+aCircle.r+" Circumference ="+circumf);
}
}
Radius=5.0 Area=78.5
Radius=5.0 Circumference =31.400000000000002
Class example
Multiple class
Constructors
Arguments & Parameters
Passing object to method
Modifier
ตารางแสดงชนดของ Modifier (หรอ Accessibility)
Modifier การใชงาน
static ใชนยามตวแปรและเมธอด ทตองการใหมคาคงท สามารถน าไปใชไดกบทกๆ สวนของClass โดยคานนจะไมมการเปลยนแปลงไมวากรณใดๆ
public ใชนยามตวแปร, เมธอด และคลาส ใด ๆ เพอใหสามารถน าไปใชกบคลาสหรอโปรแกรมอน ๆ ได
private ใชนยามตวแปร หรอเมธอด เพอใหเรยกใชไดเฉพาะภายในคลาส ทสรางตวแปรหรอเมธอดนน ขนมาเทานน
protected ใชนยามตวแปรหรอ เมธอด ทใชไดเฉพาะคลาส ทสรางขนมาดวยวธการสบทอด (Inheritance) เทานน โดยปกตจะใช Protected กบ คลาส ทเปน คลาสตนฉบบ (Base Class)
void ใชนยามเมธอด โดยเปนการก าหนดใหไมมการสงคาใดๆ กลบมาใหกบ เมธอดน (ดงนนจงไมตองใชค าสง return)
modifier
◼ ถาหากไมมการระบคาไว จะหมายถง❑ ตวแปร
◼ ใชไดเฉพาะในเมธอดทนยามตวแปรนนไว
❑ เมธอด◼ ใชไดเฉพาะภายใน คลาส นนเทานน คลาสอนจะเรยกใชไมได
❑ คลาส◼ ใชไดเฉพาะภายในโปรแกรม (File) นเทานน โปรแกรมอนจะมาเรยกใชเมธอดหรอตวแปรตางๆ ใน
คลาส นไมไดเลย
[Static Class Members]
◼ ความหมายคลาสมสมาชกทเปนตวแปรใด ๆ สามารถใชรวมกนไดระหวาง object ทเปน instance ของคลาสเดยวกน (ปกตแยกจากกน)
◼ วธการประกาศใหตวแปรใด ๆ เปนแบบ static class members ตองมค าสงวน static น าหนาชนดขอมล เชน
private static int count = 0;
class X {
static int a = 0;
public static int methodA() {
a += 1;
return a;
}
}
class TestClassMember {
public static void main(String[]
args) {
int num = 0;
num = num +
X.methodA();
}
}
การสงคาผาน Arguments
การสงคาผานทาง arguments ทอยใน parameter list มอย 2 ลกษณะคอ
◼ Argument แบบส าเนาคาขอมล (Pass by Value Argument) ◼ Argument แบบผานคาอางถง (Pass by Reference Argument)
Pass by Value Argument
◼ คณสมบตทเรยกวา Pass by Value คอการสงขอมลไปให method และ methodกอานคาไดโดยตรง และน าไปใชงานไดตามความตองการ แตหากขอมลใน argument เกดการเปลยนแปลงไมวาจากกรณใด ๆ ภายใน method จะไมมผล กบขอมลเดม
การสงคาไปยง method แบบ pass-by-value นคาทสงเขาไปจะถกน าไปใชภายในตว method เทานน การเปลยนแปลงใด ๆ ทเกดขนจะไมมผลกระทบกบตวแปรทเปนเจาของคานน ภายนอก method เลย
Method_Name (Type Argument_Name1,
Type Argument_Name2, …)
{
… Argument_Name1 = …;
…
}
❑ Type คอชนดขอมลทก าหนดเปน int, double, float, boolean❑ Argument_Name1, Argument_Name2 คอชอ argument หากมมากกวาหนงตวจะ
ถกแยก ดวยเครองหมาย , (comma)
Pass by value
Pass by Reference Argument
◼ คณสมบตทเรยกวา Pass by Reference คอการสงขอมลไปให method น าไปใชงานไดตามความตองการ แตหากขอมลใน argument ไมวาจะเปนการเปลยนแปลง attribute หรอการสรางใหม การเปลยนแปลงดงกลาวภายใน method ขอมลทเปลยนแปลงไปจะมผลกบขอมลหลงจาก method ท างานเสรจสน
◼ การสงคาแบบอางองนน สงทเราสงเขาไปใน method นนไมใชคาของตวแปร (copy) แตเปนตวอางองถง object นน ๆ โดยตรง เราอาจพดไดวาสงทเราสงไปนน เปนทอย (address) ของ object นน ๆ กได
◼ ลกษณะการสงขอมล argument จะไมใชการส าเนาขอมลเพอน าไปใชงานภายใน method แตใน method จะไดรบเปน จดอางถง (address) หรอจดทเชอมโยงไปหา object ดงนนจงเรยกการสงขอมล แบบนวาการผานคาอางถง
Method_Name (Class_Name Argument_Name1, Class_Name Argument_Name2, …)
{ Argument_Name1.Attribute_Name =
…;
Argument_Name2.Method_Name();
… }
❑ Class_Name คอชอ class ทเปนทมาของ object ทจะสงมาเปน argument❑ Argument_Name1, Argument_Name2 เปน argument ทถกสรางขนมาแบบ object
(สรางมาจาก class ดวยค าสง new)
Passing object to method
Package
◼ โปรแกรมทมขนาดใหญ จะประกอบดวย class จ านวนมาก เราสามารถจดหมวดหมใหเปนระเบยบและงายตอการใชงานได ดวยการแยก source code ของโปรแกรมหนงโปรแกรมใหเปนหลาย file ในกรณน source code ไมจ าเปนตองม method main() อย ยกเวนซอรสโคดทมคลาส คลาสแรกทเราใชเรยกโปรแกรมหลกของเรา
◼ เราเรยก file ทประกอบดวยคลาสตงแตหนงคลาสขนไปแตไมมคลาสทมเมออด main() อยวา แพคเกจ
◼ เปนทรวมของ class ตาง ๆ ทถกเรยกใชในโปรแกรม เพอท าใหการเรยกใช class ตาง ๆ เหลานท าไดงายขน
Package
◼ คอการรวมกลมของคลาสไวในชดเดยวกน◼ เพอความสะดวกในการอางองถงเพอใชงาน◼ ท าใหการจดเกบ Bytecodes เปนไปอยางมระบบ◼ ใชหลกเกณฑการจด package เปนไปตามการจด Directory ของระบบ◼ ท าใหเกดรปแบบหนงของการก าหนดระดบการเขาถง
Java Package
Package
◼ ค าสงในการเรยกใช Package คอ ค าสง import
◼ ตวอยางการใชงาน❑ import java.util.*;
หมายถง เรยกใช Package ชอ “java.util” ทง Package (ทก Class)❑ import java.util.ArrayList;
หมายถง เรยกใชเฉพาะ Class ชอ “ArrayList” ซงอยใน Library ชอ “java.util”
Class Declaration Every program must include at least one class.
Encapsulation (Protection)
Encapsulation : คอรากฐานอยางหนงของแนวคดในเชง Object-OrientedซงขอดของEncapsulation คอการปองกน Attribute ของ Object จากความเสยหาย
Encapsulation คอการหอหม Attribute และ Methods เขาไวดวยกน
Encapsulation จะท าหนาทปองกนมให Object อนทอยภายนอก เขาถงObject หนงๆ ไดอยางอสระจะมเฉพาะ Methods ทอยใน Object เทานนจะสามารถตดตอกบ Attribute ทอยใน Object เดยวกนได
Encapsulation
◼ หมายถงการจะเรยกใชคณลกษณะของวตถ จะท าไดโดยการเรยกผานเมธอดเทานน
◼ หลกการของการหอหม คอการก าหนดใหคณลกษณะของออปเจคมคณสมบตเปน private และก าหนดใหเมธอดมคณสมบตเปน public
◼ โดยมเมธอด get / set ไวเพอเขาถง data นนๆจะเรยกวา class นน ๆ เปน Full Encapsulation class
Encapsulation
◼ การก าหนดการเขาถง ใน C++ ก าหนดไว 3 ระดบดงน❑ Public
❑ Protected
❑ Private
JAVA
public private
Attribute ใหภายนอกเขาใชงานได ใชไดส าหรบภายในเทานน
Method ใชตดตอกบภายนอก ใชภายใน class เทานน
Encapsulation
◼ จะใช Access Modifiers ในการเขาถงขอมล และ method
❑ Public class อนภายนอก สามารถทจะเขาถงใด❑ Private class อนภายนอก ไมสามารถเขาถงใด❑ Protected class ทถกสบทอดมาเทานนทสามารถใชได❑ ถาไมก าหนด จะถอวา friendly หรอ default โดยจะเปน public ใน
package เดยวกน แตเปน Private ส าหรบ package อน
Encapsulation
Inheritance
◼ การถายทอดคณสมบตไปยงClass ลก❑ Class ทเปนตนแบบเรยกวา Superclass
❑ Class ทไดรบการสบทอดคณสมบตเรยกวา Subclasses
❑ Class หนงจะม Superclass ได Class เดยว
◼ ซงประโยชนของ Inheritance คอ❑ ท าใหมโครงสรางทเปนระบบ ระเบยบ ปรบเปลยนไดงาย❑ ลดเวลาในการพฒนาระบบ❑ ลดคาใชจายในการพฒนา
Inheritance
◼ Java ใช extends ชอclass
◼ ในการสบทอด◼ class x extends y
◼ {
◼ }
Class x
Class y
◼ Constructors
❑ เปน method พเศษทจะถกเรยกใหท างานตอนท Object ถกสรางขนมา❑ คลาส ๆ หนงอาจม Constructor หลายตวได แตตองม Argument ตางกน
เรยกวา Overloading Constructors โดยพารามเตอรทสงไปยง constructor ตองมจ านวนไมเทากน หรอ ถาจ านวนเทากน ชนดของพารามเตอรตองไมเหมอนกน
❑ สวนใหญจะน ามาใชในการก าหนดคาเรมตนใหกบ Object
❑ รปแบบการใชใน Java คอ public Classname()
Constructors
constructors
final
◼ ถาระบอยหนา class จะท าให class อนๆไมสามารถทจะสบทอดคณสมบตของ class ทระบ final ได
◼ ถาระบอยหนา method จะท าให class ทสบทอดไปไมสามารถทจะ Override
method นได
final class sample
{ …..
}
class test extends sample
{}
Composition
Car
Wheel
Door
Engine
Class car{
Wheel [] theWheel = new Wheel[4];
Door [] theDoor = new Door[2];
Engine theEngine = new Engine();
}
Polymorphism
◼ วตถตาง ๆ ทมพฤตกรรมแบบเดยวกนอยในตว แตรายละเอยดวธการกระท าอาจแตกตางกนได ขนอยกบวาวตถนนถกน าไปใชแบบใดo เชน วตถ “SQUARE” และวตถ “CIRCLE” ตางกสามารถถก
“calculateArea” ได แตวธการ “calculateArea” ของทง 2 วตถอาจไมเหมอนกน
◼ วตถตาง ๆ มวธคณลกษณะ และรายละเอยดวธการกระท าทแตกตางกน แตมองใหเหมอนกนได จากคณลกษณะและพฤตกรรมทวตถเหลานนมรวมกนo เชน วตถ “SQUARE” และวตถ “CIRCLE” มวธการ
“calculate Area” ตางกน แตสามารถมองคณสมบตรวมกนอนไดแก ทง 2 วตถ ตางกเปน วตถ “SHAPE” ทสามารถ “calculate Area” ได
polymorphism
◼ public interface Vegetarian{}
◼ public class Animal{}
◼ public class Deer extends Animal implements Vegetarian{}
A Deer IS-A Animal
A Deer IS-A Vegetarian
A Deer IS-A DeerA Deer IS-A Object
Deer d = new Deer();
Animal a = d;
Vegetarian v = d;Object o = d;
Example
/* File name : Employee.java */
public class Employee {
private String name;
private String address;
private int number;
public Employee(String name, String address, int number) {
System.out.println("Constructing an Employee");
this.name = name;
this.address = address;
this.number = number;
}
public void mailCheck() {
System.out.println("Mailing a check to " + this.name + " " +
this.address);
}
public String toString() {
return name + " " + address + " " + number;}
public String getName() {
return name;
}
public String getAddress() {
return address;
}
public void setAddress(String newAddress) {
address = newAddress;
}
public int getNumber() {
return number;
}}
/* File name : Salary.java */
public class Salary extends Employee {
private double salary; // Annual salary
public Salary(String name, String address, int number, double
salary) {
super(name, address, number);
setSalary(salary);
}
public void mailCheck() {
System.out.println("Within mailCheck of Salary class ");
System.out.println("Mailing check to " + getName()
+ " with salary " + salary);
}
public double getSalary() {
return salary;
}
public void setSalary(double newSalary) {
if(newSalary >= 0.0) {
salary = newSalary;
}
}
public double computePay() {
System.out.println("Computing salary pay for " +
getName());
return salary/52;
}}
/* File name : VirtualDemo.java */
public class VirtualDemo {
public static void main(String [] args) {
Salary s = new Salary("Mohd Mohtashim", "Ambehta, UP", 3, 3600.00);
Employee e = new Salary("John Adams", "Boston, MA", 2, 2400.00);
System.out.println("Call mailCheck using Salary reference --");
s.mailCheck();
System.out.println("\n Call mailCheck using Employee reference--");
e.mailCheck();
}}
Constructing an Employee
Constructing an Employee
Call mailCheck using Salary reference --
Within mailCheck of Salary class
ailing check to Mohd Mohtashim with salary 3600.0
Call mailCheck using Employee reference--
Within mailCheck of Salary classailing check to John Adams with salary 2400.0
Reference code:https://www.tutorialspoint.com/java/java_abstraction.htm
Polymorphism
◼ หมายถง การบอกแบบเดยว แตไดรบการสนองไดหลายแบบ
◼ Overloading
❑ Method มชอซ ากนไดแตม argument แตกตางกน
◼ Overriding
❑ น า Method ของ Superclass มาจดการไดเอง
Overloading Methods
◼ เมธอดใดๆ ทสามารถรบคาทเปนตวแปรไดหลากหลายชนดได ถาก าหนดไวเปนเมธอดเดยว อาจท าใหผลลพธทไดเกดความผดพลาดได
◼ เมธอดเดยวกน แตสรางใหเมธอด มชนดของตวแปรใน parameter list ตางกน ◼ เมอมการใชเมธอด ชอนโปรแกรมจะเรยกเมธอดทมชนดของตวแปรตรงกบทตองการโดยอตโนมต ◼ เรยกวอการนวา “Overloading” และเรยกเมออดทใชวอการนวา “Overloading Methods”
Overloading
public int add(int x, int y)
{ return x+y;
}
public double add(double x, double y)
{ return x+y;
}
public int subtract(int x, int y)
{ return x-y;
}
public double subtract(double x, double y)
{ return x-y;}
Overriding
◼ เปนการจดการ implement
◼ method ทเปนของ Super
Class
abstract class And Methods
◼ ใชส าหรบ ให class อน ๆ สบทอดไปใชงาน◼ ไมสามารถ ทจะสราง object จาก class
abstract ได
abstract class And Methods
testAbstractClass t=new testAbstractClass();
Error
abstract class And Methods
จ าเปนตอง Override
Interfaces
◼ มลกษณะ เหมอน Abstract Class แตจะไมม fields
◼ จะไมมการ implement Code ภายใน methods
ประกาศ
เรยกใช
Interfaces
Graphical User Interface (GUI)
Applications
148
Abstract Windowing Toolkit (AWT)
Events Handling
Swing
AWT - Abstract Windowing Toolkit
◼ Single Windowing Interface on Multiple Platforms
◼ Supports functions common to all window systems
◼ Uses Underlying Native Window system
◼ AWT provides❑ GUI widgets
❑ Event Handling
❑ Containers for widgets
❑ Layout managers
❑ Graphic operations
149
AWT - Abstract Window Toolkit
◼ Portable GUI - preserves native look and feel
◼ Standard GUI Components (buttons…)
◼ Containers - Panels, Frames, Dialogs
◼ Graphics class for custom drawing
◼ Layouts responsible for actual positioning of components:
❑ BorderLayout, GridLayout, FlowLayout, Null layout
150
Building Graphical User Interfaces
◼ import java.awt.*;
◼ Assemble the GUI
❑ use GUI components,
◼ basic components (e.g., Button, TextField)
◼ containers (Frame, Panel)
❑ set the positioning of the components
◼ use Layout Managers
◼ Attach events
151
A sample GUI program
import java.awt.*;
public class MyGui
{
public static void main(String args[] )
{
Frame f = new Frame ("My Frame");
Button b = new Button("OK");
TextField tf = new TextField("Programming in Java", 20);
f.setLayout(new FlowLayout());
f.add(b);
f.add(tf);
f.setSize(300, 300);
f.setVisible(true);
}
}
152
Events
◼ Each GUI component (e.g., a Button) that wishes to respond to an event type (e.g., click), must register an event handler, called a Listener.
◼ The listener is an object of a "Listener" interface.
◼ A Listener class can be created by subclassing (through "implements") one of Listener interfaces (all listener inrefaces are in the java.awt.event package = > must import java.awt.event.*; )
◼ The registration of the listener is done by a call to a method such as addActionListener(<Listener Object>). Each GUI component class has one or more such add…() methods, where applicable.
153
Events
154
b.addActionListener( );
method to add a listener listener objectButton
f.addWindowListener( );
Frame
Listener Interfaces in java.awt.event.*
◼ [1] ActionListener
◼ [2] ItemListener
◼ [3] MouseMotionListener
◼ [4] MouseListener
◼ [5] KeyListener
◼ [6] FocusListener
◼ [7] AdjustmentListener
◼ [8] ComponentListener
◼ [9] WindowListener
◼ [10] ContainerListener
◼ [11] TextListener
155
Listener Interfaces
◼ Each listener interface has methods that need to be implemented for handling different kinds of events.
◼ For example 1, the ActionListener interface has a method actionPerformed() button component is operated.
◼ For example2, the MouseMotionListener interface has two methods: ❑ 1) mouseDragged(MouseEvent) - Invoked when a mouse button
is pressed on a component and then dragged.
❑ 2) mouseMoved(MouseEvent) - Invoked when the mouse button has been moved on a component (with no buttons down).
156
Implementing the ActionListener Interface and
attaching an event handler to a button
import java.awt.*;
import java.awt.event.*;
public class MyGui1
{
public static void main(String args[] )
{
Frame f = new Frame ("My Frame");
MyGuiAction ga = new MyGuiAction(f);
}
}
class MyGuiAction implements ActionListener
{
static int count = 0;
Button b;
TextField tf;
MyGuiAction(Frame f)
{
157
b = new Button("OK");
b.addActionListener(this);
tf = new TextField("Hello Java", 20);
f.setLayout(new FlowLayout());
f.add(b);
f.add(tf);
f.setSize(300, 300);
f.setVisible(true);
}
public void actionPerformed( ActionEvent e)
{
if(e.getSource() == b)
{
count++;
System.out.println("Button is Pressed");
tf.setText("Hello Java Click "+count);
}
}
}
BorderLayout Example
import java.awt.*;
public class MyGui2
{
public static void main(String args[] )
{
Frame f = new Frame ("My Frame");
f.setLayout(new BorderLayout());
// Add text field to top
f.add("North",new TextField());
// Create the panel with buttons at the bottom...
Panel p = new Panel(); // FlowLayout
p.add(new Button("OK"));
p.add(new Button("Cancel"));
f.add("South",p);
f.add("Center", new TextField("Center region"));
f.setSize(300, 300);
f.setVisible(true);
}
}
158
AWT to Swing
◼ AWT: Abstract Windowing Toolkit◼ import java.awt.*
◼ Swing: new with Java2◼ import javax.swing.*
◼ Extends AWT
◼ Tons o’ new improved components
◼ Standard dialog boxes, tooltips, …
◼ Look-and-feel, skins
◼ Event listeners
Object
Component
Container ButtonList
Scrollbar
Label
Canvas
WindowJComponent
Scrollpane
Swing does not replace the AWT; it is built on top of it
All 1.0 AWT components are heavyweight; corresponding Swing components are lightweight
Swing component names begin with ``J'': Component (AWT) vs. JComponent (Swing) Button (AWT) vs. JButton (Swing)
Always use Swing components; however, since Swing is built on top of AWT, you will need to know some AWT methods
JComponent
AbstractButton
JButton JMenuItem
JToggleButton
JCheckBox
JLabel
JList
JScrollBar
JFileChooser
Note that JComponents are containers
JComponents do not extend their AWT counterparts: For example, the JButton class is not a subclass
(direct or indirect) of Button
However, some Swing components are not JComponents
For example, some Swing containers are direct subclasses of their AWT counterparts
Container
JComponent Panel
ScrollPane
Window
Dialog Frame
Applet
Container
JComponent Panel
ScrollPaneWindow
Dialog Frame Applet
JDialog
JWindow
JFrame JApplet
JComponent
JLayeredPane JPanel
JScrollPane
JInternalFrame
JDesktopPane
JTableJTree
Object Oriented Analysis and Design
168
◼ Object Oriented Analysis❑ Determine what to do
❑ Extract Objects (modules)
◼ Object Oriented Design❑ Determine how to build
◼ Unified Modeling Language (UML) ❑ Is a modeling language for documenting OO Analysis
and Design.
169
Solving the Problem
◼ Step 1 - Write Requirements for the system
❑ Should be clearly written and unambiguous
❑ Should be implementable
❑ Should be testable
❑ Is not a part of this course
◼ Step 2 – Analysis, Design (Modeling)
❑ You will be learning in this section…..
◼ Step 3 – Implementation
❑ You already know…..
170
Analysis, Design and Implementation
◼ Proper analysis and design (modeling) prior
to implementation results in a high quality
product.
◼ Successful projects spend most time on
analysis, less on design and even less time
on implementation.
Analysis Design Implementation
Software Development Process and Unified
Modeling Language (UML)
◼ A software development process is a set of phases that are followed to bring a product or a system from conception to delivery.
◼ In the Unified Process, there are four of these phases:❑ Analysis phase
◼ identify the system we are going to develop, including what it contains and its business case.
◼ UML: use-case diagrams
❑ Design phase◼ perform detailed design and identify the foundation of system from “use case
diagram”, which eventually lead to classes.
◼ UML: classes, objects, class diagrams, sequence diagram, collaboration diagrams etc.
❑ Implementation phase (write software using Java/C++)◼ the actual building of the product from the design of the system.
❑ Transition (Rolling out phase): Deliver the system/product to the users. Includes maintenance, upgrades, and so on until phasing out.
172
Introduction to UML
◼ Is a graphical modeling language that can be
used represent the artifacts of analysis and
design.
◼ It is a standard that has international support.
◼ Was developed by Rational Software –
❑ Grady Booch, Jim Rumbaugh and Ivar Jacobson
173
UML – Building Blocks
◼ Elements (Things)
❑ e.g. classes, interfaces etc
◼ Relationships
❑ e.g. association, generalization
◼ Diagrams
❑ e.g. class diagrams, use case diagrams
174
UML - Elements
centreX:IntcentreY:Int=0
Circle
draw() move(Int X, Int Y)
centreX:IntcentreY:Int=0
CircleA:Circle
draw() move(Int X, Int Y)
Class Object
<<interface>>
TypeWriter
keyStroke()
Interface
Borrow
Use-case
Actor
Shapes
Component
UML - Relationships
◼ Dependency
◼ Association
◼ Generalization
◼ Realization
UML - Diagrams
◼ Structural Diagrams❑ Visualize, specify, construct and document the
STATIC aspects of the system.
◼ Behavioral Diagrams❑ Visualize, specify, construct and document the
DYNAMIC aspects of the system.
UML– Diagrams – cont..
Structural
Class Diagram
Object Diagram
Component Diagram
Deployment Diagram
Behavioral
Use case Diagram
Sequence Diagram
Collaboration Diagram
Statechart Diagram
Activity Diagram
UML– Diagrams - Notes
◼ Class Diagram shows a set of classes, interfaces and
their relationships.
◼ Object Diagram shows a set of objects and their
relationships.
◼ Component Diagram shows the organization and
dependencies among a set of of components.
◼ Deployment Diagram shows the configuration of run
time processing nodes.
UML– Diagrams - Notes
◼ Use Case Diagram shows use cases, actors and their
relationships.
◼ Sequence Diagram shows the interaction between
actors and objects and other objects of the system in
ordered based on the time they occur.
◼ Collaboration Diagram shows the structural
organization of the objects that send and receive
messages.
◼ Statechart Diagram shows a state machine consisting
of states, transitions an events.
◼ Activity Diagram used to analyze the bahaviour within
more complex use-cases.
Life Cycle Phase
◼ Requirements
◼ Object Oriented Analysis
◼ Object Oriented Design
◼ Development
◼ Deployment
Analysis
Activity Diagram
Use-case DiagramUnderstand
System Usage
UML DiagramActivity
Identify Classes
Define Workflows
High Level Class Diagram
Design
Sequence and
Collaboration Diagram
Identify Interactions
among objects
State DiagramAnalyze State
Changes
Class DiagramRefine Class
Diagrams
UML DiagramActivity
Use Case Diagrams
Introduction
◼ Getting started is the most difficulty part of any new process.
◼ In software modelling, the first thing you need to do is understand what are you going to model and ultimately develop.
◼ Creating a highest form details about a system--use case diagram--is an almost natural point of origin for the software design.
◼ A use case diagram is an excellent way to communicate to management, customers, and other non-development people what a system will do when it is completed.
University Record System (URS)
◼ A University record system should keep information about its students and academic staff.
◼ Records for all university members are to include their id number, surname, given name, email, address, date of birth, and telephone number. ❑ Students and academic staff each have their own unique ID
number: studN (students), acadN (academic employee), where N is an integer (N>0).
◼ In addition to the attributes mentioned above: ❑ Students will also have a list of subjects they are enrolled in. A
student cannot be enrolled in any more than 10 subjects.
❑ Academic employees will have a salary, and a list of subjects they teach. An academic can teach no more than 3 subjects.
Some Actions Supported by URS
◼ The system should be able to handle the
following commands.
❑ Add and remove university members (students,
and academic staff)
❑ Add and Delete subjects
❑ Assign and Un-assign subjects to students
❑ Assign and Un-assign subjects to academic
staff.
Use Case Diagrams
◼ Use Case diagrams show the various activities the users can perform on the system.
❑ System is something that performs a function.
◼ They model the dynamic aspects of the system.
◼ Provides a user’s perspective of the system.
Use Case Diagram - URS System
systemuser academic
student
URS
del member
add member
add subject
del subject
assg subject
unass subject
enrol subject
unenrol subject
Use Case Diagrams
◼ A set of ACTORS : roles users can play in interacting with the system.❑ An actor is used to represent something that users our
system.
◼ A set of USE CASES: each describes a possible kind of interaction between an actor and the system.❑ Uses cases are actions that a user takes on a system
◼ A number of RELATIONSHIPS between these entities (Actors and Use Cases).❑ Relationships are simply illustrated with a line
connecting actors to use cases.
Use Case Diagrams - Actors
◼ An actor is a user of the system playing a
particular role.
◼ Actor is shown with a stick figure.
employee clientemployer
Use Case Diagrams – Use Cases
◼ Use case is a particular activity a user can do
on the system.
◼ Is represented by an ellipse.
◼ Following are two use cases for a library
system.
ReserveBorrow
Use Case Diagram – Example (Library)
client employee
supervisor
library system
borrow
reserve
Order title
Fine payment
Use Case Diagrams - Relationships
◼ Inclusion❑ Inclusion enables to reuse one use case's steps inside
another use case.
◼ Extension❑ Allows creating a new use case by adding steps to
existing use cases
◼ Generalization❑ Allows child use cases to inherit behavior from parent
use cases
Use Case – Example (self service
machine)
Restock
Supplier
Self service machine
Buy a product
customer
Self service machine
Collect Money
Self service machine
Collector
Use Case – Example (self service machine – includes
relationship)
Close Machine
Restock
Close Machine
Open Machine
<<includes>>
<<includes>>
CollectOpen Machine
<<includes>>
<<includes>>
Use Case – Example (self service machine –
extends relationship)
Restock
Close Machine
Open Machine
<<includes>>
<<includes>>
Restock According
to Sales
<<extends>>
Use Case – Example (self service machine – generalize
relationship): Actor-to-Actor relationship
Supplier Agent
Restocker Collector
generalized actor
specialized actor
Use Case – Example (self service
machine)
Close Machine
Restock
Close Machine
Open Machine
<<includes>>
<<includes>>
Collect
Open Machine
<<includes>>
<<includes>>
Buy a product
Restock according to sales
customer
supplier
Self Service Machine
199
Class Diagrams
200
Identify Classes (Extract Nouns)
❑ A University record system should keep information about its students and academic staff.
❑ Records for all university members are to include their idnumber, surname, given name, email, address, date of birth, and telephone number.
◼ Students and academic staff each have their own unique ID number: studN (students), acadN (academic employee), where N is an integer (N>0).
❑ In addition to the attributes mentioned above:
◼ Students will also have a list of subjects they are enrolled in. A student cannot be enrolled in any more than 10 subjects.
◼ Academic employees will have a salary, and a list of subjects they teach. An academic can teach no more than 3 subjects.
201
Nouns which are potential classes
❑ A University record system should keep information about its students and academic staff.
❑ Records for all university members are to include their idnumber, surname, given name, email, address, date of birth, and telephone number.
◼ Students and academic staff each have their own unique ID number: studN (students), acadN (academic employee), where N is an integer (N>0).
❑ In addition to the attributes mentioned above:
◼ Students will also have a list of subjects they are enrolled in. A student cannot be enrolled in any more than 10 subjects.
◼ Academic employees will have a salary, and a list of subjects they teach. An academic can teach no more than 3 subjects.
202
Classes identified in the first pass
❑ UniversityRecordSystem - URS
❑ Student
❑ Academic Staff
❑ UniversityMembers
❑ Subject
URS - High Level Class Diagram
URSDataBase
UniversityMember
AcademicStaff Student
Subject
1
*has
1
*
has
teaches
0..3
1
takes *
0…10
Modeling a class in UML
◼ When modeling a class in UML, we have a lot of flexibility.
◼ The same class can be modeled in four different ways:❑ With no attributes or operations shown
❑ With only the attributes shown
❑ With only the operations shown
❑ With both the attributes and operations shown
◼ The name of the class is always the first component of the class box; in fact, it is the only required component, as we have seen in our earlier discussion (OOP in Java).
Classes (with no members)
ClassName
Circle
Notes
◼ Class - The rectangle is the icon for the class. The
name of the class is, by convention, a word with an
initial uppercase letter. It appears near the top of the
rectangle. If your class name has more than one word
name, then join the words together and capitalize the
first letter of the every word.
Classes (with attributes and operations)
attr1:type1
attr2:type2=“def”
ClassName
centreX:IntcentreY:Int=0
Circle
attr1:type1
attr2:type2=“def”
ClassName
operation1()operation2(args)operation3() : ret type
centreX:IntcentreY:Int=0
Circle
draw() move(Int X, Int Y)
Notes
◼ Attribute - An attribute is a property of a class. It describes a range of values that the property may hold in objects of the class. A class may have zero or more attributes. A one-word attribute name is written in lowercase letter. If the name consists of more than one word, the words are joined and each word other than the first word begins with an uppercase letter. The list of attribute names begins below a line separating them from the class name.
◼ Operations : An operation is something that a class can do, or that you (or another class) can do to a class. Like an attribute name, an operation's name is written in lowercase letter. If the name consists of more than one word, the words are joined and each word except the first word begins with an uppercase letter. The list of operations begins below a line separating operations from the attributes.
Class Visibility
◼ public level +
◼ protected level #
◼ private level -
- centreX:Int- centreY:Int=0
Circle
+ draw() # move(Int X, Int Y)
Notes
◼ Visibility - Visibility applies to attributes or operations,
and specifies the extent to which other classes can use a
given class's attributes or operations. Three levels of
visibility are possible (last symbols are used in UML
classes to indicate different levels of visibility):
◼ public level - usability extends to other classes +
◼ protected level - usability is open only to classes that
inherit from original class #
◼ private level - only the original class can use the
attribute or operation -
Class Multiplicity
◼ A multiplicity in a class specifies the number of instances (objects) of that class that can exist simultaneously.
◼ Only one Library object is allowed in the system (referred to as a singleton object).
◼ Default multiplicity is 0 or more (if not specified)
Library1
Class - Implementation
public class Circle {
private int centreX, centreY; // centre of the circle
//Methods to return circumference and area
protected double move() {
// Implementation here
}
public double draw() {
// Implementation here
}
}
Objects: Instances of Classes
d1: Department : Department
d1: Department
name = “Sales”deptNo = 1
: Department
name = “Sales”deptNo = 1
(a) (b)
(c) (d)
Notes
◼ Figures (a)-(d) show four possible
representations of objects.
❑ Top –
◼ objectName:ClassName – underlined or
◼ :ClassName – underlined
❑ Bottom –
◼ Attribute names and values.
Classes, Objects, and Packages
◼ Packages are a way of grouping classes into common categories.
◼ Classes and Objects are modeled when showing the package they belong to. Classes and objects will interact with classes and objects of different packages—this is how packages are tied together to create a system.
◼ A package is expressed by appending the name of package and a double colon before the class name in either a class or an object.
PackageName::ClassName
ObjectName:Packagename::ClassName
Class Relationships
◼ Classes can related to each other through
different relationships:
❑ Association (delegation)
❑ Generalization (inheritance)
❑ Realization (interfaces)
❑ Dependency
Association
◼ Association describes a link, a link being a
connection among objects between classes.
◼ Association is shown by a solid line between
classes.
Association - Example
◼ A Person works for a Company.
Person Company
employee employer
works for
Association Name
Role
Association - Properties
◼ Name❑ Name of the association
◼ Role❑ The specific role of the association
◼ Multiplicity❑ Indicates the number of objects that are connected
◼ Type❑ Plain association, aggregation, composition
◼ Direction❑ Direction can also be shown for a association
Notes
Name : “works for” Is the name of the relationship.
Role : Person plays the role employee and the Company
plays the role employer.
Multiplicity : Many employees to one company.
Type : This shows a plain association (normally referred to
as association)
Association - Multiplicity
◼ Multiplicity on association specify properties of the number of links that can exist between instances (objects) of the associated classes.❑ That is, it indicates how many objects of one class
relate to one object of another class. It is indicated by a single number or a range of numbers.
◼ We can add multiplicity on either end of class relationship by simply indicating it next to the class where the relationship enters.
Class1 Class2Association name
multiplicitymultiplicity
Association - Multiplicity
◼ A Student can take up to five Courses.
◼ Student has to be enrolled in at least one course.
◼ Up to 300 students can enroll in a course.
◼ A class should have at least 10 students.
Student Coursetakes10..300 1..5
Association - Multiplicity
◼ A teacher teaches 1 to 3 courses (subjects)
◼ Each course is taught by only one teacher.
◼ A student can take between 1 to 5 courses.
◼ A course can have 10 to 300 students.
Teacher Courseteaches 1..3
Association – Multiplicity
1
Studentstakes
1..5
10..300
Association - Multiplicity
◼ Company can have many employees. An employee can
only work for one company.
Person Companyemployee
works for
employer
1
Association - Multiplicity
*
John: Person
James: Person
Microsoft: Company
Association - Multiplicity
class Company{
Vector employee;
public Company(){
employee = new Vector();
}
public static void addEmployee(Employee emp){
employee.addElement(emp);
}
public static void removeEmployee(Employee emp){
empoyee.removeElement(emp);
}
}
class Employee{
………
}
Association - Implementation
Association - Multiplicity
◼ A Student can take many Courses and many Students
can be enrolled in one Course.
Student Coursetakes* *
Alice: Student
Jill: Student
254: Course
253: Course
Notes
◼ One class can be relate to another in a
❑ One-to-one
❑ One-to-many
❑ One-to-one or more
❑ One-to-zero or one
❑ One-to-a bounded interval (one-to-two through twenty)
❑ One-to-exactly n
❑ One-to-a set of choices (one-to-five or eight)
Notes
◼ Multiplicity can be expressed as,
❑ Exactly one - 1
❑ Zero or one - 0..1
❑ Many - 0..* or *
❑ One or more - 1..*
❑ Exact Number - e.g. 3..4 or 6
❑ Or a complex relationship – e.g. 0..1, 3..4, 6..*would mean any number of objects other than 2 or 5
Association - Self
◼ An association that connects a class to itself
is called a self association.
Association - Self
◼ A Company has Employees.
◼ A single manager is responsible for up to 10 workers.
Employeemanager
workerResponsible
for
1
0..10
Class Relationships
▪ Association
▪ Generalization
▪ Realization
▪ Dependency
Generalization (Inheritance)
◼ Child class is a special case of the parent
class
SuperClass
SubClass1 SubClass2
Generalization (Inheritance) e.g.
Circle
GraphicCircle
Inheritance - Implementation
public class Circle {
}
public class GraphicCircle extends Circle {
}
Abstract Class
Shape
Circle Rectangle
Abstract Methods (Operations)
Shape
Circle Rectangle
draw()
draw() draw()
Abstract class and method Implementation
public abstract class Shape {
public abstract draw(); //declare
without implementation
………}
public class Circle {
public draw(){
…….
}
…..
}
Class Relationships
▪ Association
▪ Generalization
▪ Realization
▪ Dependency
Realization- Interface
<<interface>>
TypeWriter
ctl()
pageDown()
brandName
numOfKeys
Keyboard
keyStroke()
◼ Interface is a set of operation the class
carries out
ctl()
pageDown()
brandName
numOfKeys
Keyboard
TypeWriter
OR
Realization - Implementation
public interface TypeWriter {
void keyStroke()
}
public class KeyBoard implements TypeWriter {
public void keyStroke(){
………
}
}
Class Relationships
▪ Association
▪ Generalization
▪ Realization
▪ Dependency
Dependency
◼ Change in specification of one class can
change the other class. This can happen
when one class is using another class.
Circle
PointMove(p:Point)
◼ Dependency relationship can be used to
show relationships between classes and
objects.
Circle
circleA:Circle
circleB:Circle
Class Diagrams
◼ The UML class diagram consists
of several Classes, connected
with Relationships.
Class Diagram - Example
◼ Draw a class diagram for a information modeling system for a school.❑ School has one or more Departments.
❑ Department offers one or more Subjects.
❑ A particular subject will be offered by only one department.
❑ Department has instructors and instructors can work for one or more departments.
❑ Student can enrol in upto 5 subjects in a School.
❑ Instructors can teach upto 3 subjects.
❑ The same subject can be taught by different instructors.
❑ Students can be enrolled in more than one school.
Class Diagram - Example
❑ School has one or more Departments.
School Departmenthas1 1..*
◼ Department offers one or more Subjects.
◼ A particular subject will be offered by only one department.
Department Subjectoffers1 1..*
Class Diagram - Example
◼ Department has Instructors and instructors can
work for one or more departments.
assigned to1..*
Instructor Department1..*
◼ Student can enrol in upto 5 Subjects.
Student Subjecttakes* 0..5
Class Diagram - Example
❑ Instructors can teach up to 3 subjects.
❑ The same subject can be taught by different
instructors.
Instructor Subjectsteaches
1..*
1..3
Class Diagram - Example
❑ Students can be enrolled in more than one
school.
Student Schoolmember
*
1..*
Class Diagram Example
School Department
Student Subject Instructor
1…*
*
member
* 1..5
attends
1..3 1..*
teaches
1..*
1
1 1..*
has
1..*
1..*
assignedTo
offeres
Object Diagram
◼ Object Diagram shows the
relationship between objects.
◼ Unlike classes objects have a state.
Object Diagram - Example
c1: Company
d2: Departmentd1: Department
name=“Sales” name=”CSSE”
p1: Persont
name=“Rao”
p2: Person
name=“Raj”
manager employee
c1: Company
name=“UniMelb”
Sequence Diagram
◼ Shows how objects communicate with each other over time.❑ That is, sequence diagrams are used to model object
interactions arranged in time sequence and to distribute use case behavior to classes.
❑ They can also be used to illustrate all the paths a particular use case can ultimately produce.
◼ The sequence diagram consists of Active Objects, Messages represented as solid-line arrows, and Time represented as a vertical progression.
Sequence Diagram - Objects
◼ A life line illustrates what is happening to an
object in a chronological fashion.
:Name
Life line
Activation
Object
Sequence Diagram – Time & Messages
◼ Messages are used to illustrate communication between
different active objects of a sequence diagram.
:Name1 :Name2
Message Two
ActorMessage One
Types of Messages
◼ Synchronous (flow interrupt until the message
has completed.
◼ Asynchronous (don’t wait for response)
◼ Flat – no distinction between sysn/async
◼ Return – control flow has returned to the caller.
Sequence Diagram – Compilation
:Compiler Linker
ActorCompile
FileSystem
Load Files
Save OBJ Files
Compile files
Link
Load OBJ files
Link OBJ files
Write EXE file
Branching Flow: flow goes to different objects [if
condition is met]
:Editor FileSystem
Load File
:BinaryViewer :TextViewer
[text file]
[binary file]
Alternative Flow: flow changes to alternative
lifeline branch of the same object
Editor
Actor
Exit App
FileSystem
[delete file]
[save file]
Sequence diagram -example
◼ Use case
❑ Add Subject Use Case to URS (University Record
System):
◼ Scenario
❑ Scenario 1 : Subject gets added successfully.
❑ Scenario 2 : Adding the subject fails because the
subject is already in the database.
System Design Principles
◼ System input can take different forms. E.g.
❑ From a graphical user interface
❑ From a command file
◼ URS system should be designed such that
the functionality can be re-used.
◼ Command reading and functionality
implementation have to be separated.
Reading from a command file - example
class URS{
public static void main(String[] args){
URSDatabase u = new URSDatabase();
//Read command from file;
while ( not end of file) {
u.procCommand(cmd);
//Read next commad;
}
//Close file
}
}
execute()
Sequence Diagram – URS Add Subject
Scenario
u:URSDatabase
procCmd(cmd)
sub1:SubjectSubject(id,name)
<< create >>
parseCommand(cmd)
addSubject(sub1)
{transient}
a:AddSubCmd<< create >>
[if cmdN = ADDSUB]AddSubCmd(u,cmdA)
Creating and Deleting objects
c:Client
:Transaction
p: ODBProxy
setVales(a,d,3,4)
<<destroy>>
<<create>>
committed
setAction(a, d, 0)
{transient}
Collaboration Diagrams
◼ Class diagrams indicates what classes are part of our system, what they offer, how they relate, but they don’t tell us how they communicate.
◼ Collaboration diagrams show (used to model) how objects interact and their roles.
◼ They are very similar to sequence diagrams. Actually they are considered as a cross between class and sequence diagram.
◼ Sequence Diagrams are arranged according to Time.
◼ Collaboration Diagrams represent the structural organization of object.
◼ [Both sequence and collaboration diagrams are called interaction diagrams]
Collaboration Diagram – URS Add Subject
Scenario
u:URSDatabase
<<self>>
a:AddSubCmd
2:[if cmdN = ADDSUB]
AddSubCmd(u,cmdA)
<<local>>
{new}
{transient}
3: execute()
3.2: addSubject(sub1)
1:parseCommand(cmd)
procCmd(cmd)
sub1:Subject
3.1: Subject(id,name){new}
Collaboration Diagram – URS Add Subject
Scenario
u:URSDatabase
<<self>>
1:parseCommand(cmd)
procCommand(cmd)
class URSDatabase{private String cmdN;private String cmdA;private parseCommand(String cmd){
cmdN = ….cmdA = ….
}public procCommand(String cmd){
parseCommand(cmd);}
}
Collaboration Diagram – URS Add Subject
Scenario
u:URSDatabase a:AddSubCmd2: AddSubCmd(u,cmdA)
{new}
{transient}
class URSDatabase{private String cmdN;private String cmdA;
public procCommand(String cmd){parseCommand(cmd);if (cmdN == ADDSUB)
AddSubCmd a = new AddSubCmd(u,cmdA);}
}
Collaboration Diagram – URS Add Subject
Scenario
class abstract Command {protected String cmd;protected URSDatabase u;public abstract void execute();
}
class AddSubCmd extends Command{public AddSubCmd(URSDatabase urs, String cmd){
u = urs;// parse command and set the arguments
}public void execute(){
// implement here}
}
Collaboration Diagram – URS Add Subject
Scenario
u:URSDatabase a:AddSubCmd<<local>>
3: execute()
class URSDatabase{private String cmd;public procCommand(String cmd){
parseCommand(0); if (cmd == ADDSUB){
AddSubcmd a = new AddSubCmd(……);}a.execute();
}}
Collaboration Diagram – URS Add Subject
Scenario
a:AddSubCmd
sub1:Subject
3.1: Subject(id,name)
class AddSubCmd{URSDatabase u;
public execute(){
subject sub1 = new Subject(id,name);
}}
Collaboration Diagram – URS Add Subject
Scenario
u:URSDatabase a:AddSubCmd3.2: addSubject(sub1)
class AddSubCmd{URSDatabse u;public execute(){
subject sub1 = new Subject(……);u.addSubject(sub1);
}}
Collaboration Diagram – URS Add Subject
Scenario
class URSDatabase{private String cmd;private Hashtable subjectHash = new HashTable();public procCommand(String cmd){
parseCommand(0); if (cmd == ADDSUB){
AddSubcmd a = new AddSubCmd(……);}a.execute();
}public addSubject(Subject sub);{
subjectHash.put(sub.getKey(), sub);}
}
URS -High Level Class Diagram
URSDatabase
UniversityMember
AcademicStaff Student
Subject
1
*has
1
*
has
teaches
0..3
1
takes *
0…10
Collaboration Diagrams
◼ Collaborations Diagrams show transient links
that exists between objects.
❑ <<self>> - A message from object to itself
❑ << local>> - A message sent due to the object
begin defined as a local variable in the method.
❑ <<parameter>> - The object reference was sent
as a parameter to the method.
❑ <<global>> The object is global.
Sequence Diagram – Enroll Student for subject
successfully
u:URSDatabase
procCmd(cmd)parseCommand(cmd)
execute()
{transient}
a:AssgSubCmd<< create >>
AssgSubCmd(u,cmdA)
getStudent(id)
return stu
getSubject(subId)
return sub[if stu != NULL and sub != NULL]
stu:Student
addSubject(sub)
Collaboration Diagram – Enroll Student in
Subject Scenario
u:URSDatabase
{new}
a:AssgSubCmd
2:AddSubCmd(u,cmdA)
{transient}
<<local>>
3: execute()
3.1: stu: =getStudent(id)
<<self>>
1:parseCommand()
procCmd(cmd)
stu:Student
3.3: [stu !=NULL and
sub!= NULL]:addSubject(sub){parameter}
3.2: sub: = getSubject(subId)
Collaboration Diagram – Enroll Student in
Subject (subject – implementation)
u:URSDatabase
{new}
a:AssgSubCmd
{transient}
<<local>>
3: execute()
3.1: stu: =getStudent(id)
procCmd(cmd)
stu:Student
3.3: [stu !=NULL and
sub!= NULL]:addSubject(sub){parameter}
3.2: sub: = getSubject(subId)
class AssgSubCmd{private URSDatabase u;public execute(){
Student stu = u.getStudent(id);Subject sub = u.getSubject(subId);if (stu != null && sub != null){
stu.addSubject(sub);}
}}
Sequence Diagram – Enroll Student for subject
- Failure
u:URSDatabase
procCmd(cmd)parseCommand()
execute()
{transient}
a:AssgSubCmd<< create >>
AssgSubCmd(u,cmd)
[if stu != NULL and sub != NULL]
stu:Student
addSubject(sub)
getNumSubjects()
return num
Excp[num >= 10]
return e
Reference
◼ https://www.w3schools.com/java/
◼ http://www.cplusplus.com/doc/tutorial/
◼ Nell Dale, Chip Weems and Mark
Headington. Introduction to java and software
design. ISBN 0-7637-1064-4
◼ ผศ. ธวชชย งามสนตวงศ. การเขยนโปรแกรมเชงวตถ. กรงเทพฯ: สถาบนเทคโนโลยพระจอมเกลาพระนครเหนอ. 2545
◼ รศ.ธรวฒน ประกอบพล. Java OOP. กรงเทพฯ: ซมพลฟาย, 2554.
top related