๐Ÿ› ๏ธ Lecture 10 ยท UML โ†’ Java implementation

Model to Code

ุฅุฒุงูŠ ุชุญูˆู„ ุงู„ู€ UML class diagrams ูˆ state diagrams ู„ู€ Java code ุดุบู‘ุงู„. Question 1.07 ูˆ Q1.08 ููŠ ูƒู„ ุงู…ุชุญุงู† ุจูŠุนุชู…ุฏูˆุง ุนู„ู‰ ุงู„ู…ู‡ุงุฑุฉ ุฏูŠ.

9
Chapters
3
Steps
5
Mapping Types
8
Exam Qs
01

Basic Implementation Steps

3 ุฎุทูˆุงุช ู„ุชุญูˆูŠู„ ุงู„ู€ design ู„ู€ code ุดุบู‘ุงู„.

๐Ÿ“ฆ Inputs & Output

๐Ÿ“ฅ Inputs

  • Detailed UML Class Diagram
  • UML Sequence Diagram
  • UML State Diagram (ู„ูˆ ู…ุญุชุงุฌ)

๐Ÿ“ค Output

Code โ€” implementation ู„ู„ู€ model ูƒู…ุง ู‡ูˆ ู…ูˆุตูˆู.

Other aspects: data structures, algorithms, database, UI.

STEP 1
Define Method Interface
Operation contracts โ€” pre/post conditions
STEP 2
Decide Order of Implementation
Top-down or Bottom-up
STEP 3
Implement in Code
Translate UML to Java/C++/etc.
๐Ÿ“œ Operation Contract โ€” Step 1 Detail

ุงู„ู€ method interface = name + parameters + return + visibility. ุงู„ู€ functionality ุจุชุชุญุฏุฏ ุนู† ุทุฑูŠู‚ contract:

  • Precondition โ€” ู‚ูŠูˆุฏ ุนู„ู‰ attributes ูˆุงู„ู€ actual parameters ู‚ุจู„ ุงู„ู€ call.
  • Postcondition โ€” effects ุจุนุฏ ุงู„ู€ call: instance creation/deletion ยท attribute modification ยท association formed/broken.
BankAccount.withdraw() contract
// Interface
public void withdraw(float amt) { ... }

// Contract
// Precondition:  amt > 0, amt <= balance
// Postcondition: new balance = old balance - amt
02

Order of Implementation

Top-Down vs Bottom-Up.

โฌ‡๏ธ Top-Down

ุงุจุฏุฃ ุจุงู„ู€ high-level components (e.g., OrderManager) โ†’ ุจุนุฏูŠู† ุงู„ู€ dependent components.

โœ… Advantages

  • Class A = higher level component ูˆ makes use of others.
  • Early validation of overall system.

โŒ Disadvantages

  • ู…ุญุชุงุฌ stubs (temporary implementations) ู„ู„ู€ lower classes.
โฌ†๏ธ Bottom-Up

ุงุจุฏุฃ ุจุงู„ู€ lower-level classes (e.g., Item, Product) โ†’ ุจุนุฏูŠู† ุงู„ู€ higher-level.

โœ… Advantages

  • Low-level classes stand alone.
  • ู…ููŠุด stubs ู…ุญุชุงุฌุฉ.

โŒ Disadvantages

  • ุงู„ู€ complete executable ูŠุชุฃุฎุฑ ู„ู„ู†ู‡ุงูŠุฉ.
๐Ÿ’ก ุงู„ู€ practical answerุบุงู„ุจุงู‹ hybrid: ุงุจุฏุฃ ุจู€ utility/value classes (Bottom-Up partially)ุŒ ุจุนุฏูŠู† main flow Top-Down ู…ุน stubs ุจุณูŠุทุฉ.
03

UML Class โ†’ Java Class

Basic mappings.

๐Ÿ”„ Direct Mappings
  • UML Class โ†’ Java class
  • UML Attributes โ†’ Java fields
  • UML Operations โ†’ Java methods
๐Ÿงฌ Abstract ยท Interface ยท Enum

๐Ÿ“ UML

// Abstract
Account {abstract}

// Interface
<<interface>> Payable

// Enum
<<enum>> OrderStatus
  CREATED
  SHIPPED
  DELIVERED

โ˜• Java

abstract class Account { ... }

interface Payable { ... }

public enum OrderStatus {
  CREATED, SHIPPED, DELIVERED
}
๐ŸŒณ Generalization โ†’ extends / implements
// SavingsAccount extends Account
class Account { ... }
class SavingsAccount extends Account { ... }

// Invoice implements Payable
interface Payable { ... }
class Invoice implements Payable { ... }
04

UML Types โ†’ Java Types

Direct type translations.

๐Ÿ“Š Type Conversion Table
UML TypeJava Type
Booleanboolean
Integerint
Realfloat or double
StringString

Default ุจูŠุนุชู…ุฏ ุนู„ู‰ ุงู„ู€ modeling tool. ุจุนุถ ุงู„ุฃุฏูˆุงุช ุจุชุณุชุฎุฏู… int ูƒู€ default ู„ูˆ ุงู„ู€ return value ู…ุด ู…ุชุญุฏุฏ.

05

Unidirectional Associations

ุงู„ู€ Associations ููŠ UML ุจุชุชุญูˆู„ ู„ู€ references ููŠ Java. ุงู„ู€ default multiplicity = 0..1 (reference can be null).

๐Ÿ”— Optional 0..1 Association

UML: Account [1] โ”โ†’ [0..1] DebitCard

public class Account {
  private DebitCard theCard;  // 0..1 = good match for ref

  public DebitCard getCard() { return theCard; }
  public void setCard(DebitCard card) { theCard = card; }
  public void removeCard() { theCard = null; }
}
๐Ÿ”’ Immutable Association {Immutable}

ุงู„ู€ link ุจูŠุชุนู…ู„ู‡ set ู…ุฑุฉ ูˆุงุญุฏุฉ ูˆู…ุด ุจูŠุชุบูŠุฑ. ู„ุงุฒู… explicit check:

public void setCard(DebitCard card) {
  if (theCard != null) {
    // throw ImmutableAssociationException
  }
  theCard = card;
}
โ— Compulsory Association (multiplicity 1)

ุงู„ู€ link ู„ุงุฒู… ู…ุงูŠุจู‚ุงุด null ุฃุจุฏู‹ุง. ุงุนู…ู„ enforce ููŠ ุงู„ู€ constructor:

public Account(Guarantor g) {
  if (g == null) {
    // throw NullLinkError
  }
  theGuarantor = g;  // must have a guarantor
}
06

Bidirectional Associations โญ

ุฏูŠ ุจุชูŠุฌูŠ ููŠ Question 1.07 ู…ู† ุงู…ุชุญุงู†ุงุช Fall 2021-22 / Winter 2021.

โ†”๏ธ Implementation Strategy

ุงู„ู€ References ููŠ Java ุจุทุจูŠุนุชู‡ุง unidirectional. ุนู„ุดุงู† ุชุนู…ู„ bidirectional ู…ุญุชุงุฌ 2 references โ€” ูˆุงุญุฏ ููŠ ูƒู„ class.

ุงู„ู€ key concept: Referential Integrity โ€” ุงู„ู€ links ู„ุงุฒู… ุชูุถู„ consistent.

โš ๏ธ Referential Integrity Violation

Account acc1 = new Account();
Account acc2 = new Account();
DebitCard aCard = new DebitCard(acc1);  // card โ†’ acc1
acc2.setCard(aCard);                          // acc2 โ†’ card

// PROBLEM: card.theAccount = acc1, but acc2 thinks it owns card!
// Links inconsistent โ†’ violates integrity

โœ… Solution โ€” Delegate One Class to Maintain Integrity

public class Account {
  private DebitCard theCard;

  public void addCard() {
    // Account handles BOTH creation and reference setting
    theCard = new DebitCard(this);
  }
}
07

1-to-Many & Many-to-Many

ArrayList / collection ู„ู„ู€ multiple references. ุฏู‡ ุดูƒู„ Code (a) ููŠ exam Q1.07.

๐Ÿ”ข Multiplicity โ†’ Code Pattern
1
One reference, never null
private Class field;
(check in constructor)
0..1
One reference, can be null
private Class field;
*
0 to many
private List<Class> items;
= new ArrayList<>();
1..*
1 to many
private List<Class> items;
(check size โ‰ฅ 1)
0..8
up to 8
List + size check < 8
๐Ÿ’ป Q1.07 Style โ€” Advertiser โ†” Account (1:*)

ุงู„ู€ UML: Advertiser [1] โ”โ” [*] Account

ุงู„ูƒูˆุฏ ุงู„ุตุญ (ู‡ูˆ Code A ููŠ ุงู„ู€ exam):

Correct implementation
public class Advertiser {
  private Set accounts;

  public Advertiser() {
    accounts = new HashSet();
  }

  public void addAccount(Account a) {
    if (a != null) {
      accounts.add(a);
      a.setOwner(this);   // Maintain bidirectional
    }
  }
}

public class Account {
  private Advertiser owner;  // single ref โ€” many accounts share owner

  public void setOwner(Advertiser newOwner) {
    if (newOwner != null)
      owner.addAccount(this);
  }
}
โš ๏ธ Common Wrong Versions
  • Code B: Advertiser ุนู†ุฏู‡ Account account ูˆุงุญุฏ โ€” ุบู„ุทุŒ ุงู„ู…ูุฑูˆุถ Set.
  • Code C: Account ุนู†ุฏู‡ Set of Advertiser owners โ€” ุบู„ุทุŒ ูƒุฏู‡ ุชุจู‚ู‰ many-to-many ู…ุด 1-to-many.
โ›“๏ธ Many-to-Many โ€” Two strategies
  1. Direct โ€” ูƒู„ class ูŠุญุชูุธ ุจู€ collection. ุงุฎุชุงุฑ ูˆุงุญุฏ ูŠุญุงูุธ ุนู„ู‰ ุงู„ู€ referential integrity.
  2. Reify the association โ€” ุงุนู…ู„ intermediate class ู…ุซู„ Signatory ูŠู…ุณูƒ ุงู„ุนู„ุงู‚ุฉ. ุบุงู„ุจุงู‹ ุฃู†ุถู.
08

Qualified Associations & Association Classes

HashMap ู„ู„ู€ qualifiers. ูˆ Reification ู„ู„ู€ association classes.

๐Ÿ”‘ Qualified Association โ†’ HashMap

UML: Bank [accno] โ†’ Account [0..1] โ€” efficient lookup by accno.

public class Bank {
  private HashMap<Integer, Account> accounts;

  public Account lookupAccount(int number) {
    return accounts.get(number);
  }

  public void addAccount(Account a) {
    accounts.put(a.getNumber(), a);
  }
}
๐Ÿ“Ž Association Class โ†’ 2 Associations + Reified Class

UML: Module *โ”€โ”€*โ”€โ”€ Student + attached Registration {mark}

Implementation: ุญูˆู‘ู„ู‡ุง ู„ุนู„ุงู‚ุชูŠู† ู…ู† ุฎู„ุงู„ new class.

class Registration {
  private Student student;
  private int mark;

  Registration(Student st) {
    student = st;
    mark = 0;
  }
}

public class Module {
  private List<Registration> registrations;

  public void enrol(Student st) {
    registrations.add(new Registration(st));
  }
}
09

State Diagram โ†’ Code

3 ุฎุทูˆุงุช: define states ยท track current state ยท switch on state per operation.

๐Ÿ”ข Implementation Steps
  1. Define States โ€” ุงุนู…ู„ู‡ุง constants (ุฃูˆ ุงุณุชุฎุฏู… State pattern).
  2. Track Current State โ€” ุญุฏุฏ ุงู„ู€ initial state ููŠ ุงู„ู€ constructor.
  3. Operation-by-Operation โ€” ุงุณุชุฎุฏู… switch ูˆููŠู‡ case ู„ูƒู„ state.
๐Ÿ’ป Example โ€” Account class

States: InCredit, OverDrawn, Suspended. Operations: deposit, withdraw, suspend, unsuspend.

public class Account {
  // Step 1: define states
  private final int InCredit = 0;
  private final int Overdrawn = 1;
  private final int Suspended = 2;

  private int state;
  private int historyState;
  private double bal;

  // Step 2: initial state in constructor
  public Account() {
    state = InCredit;
  }

  // Step 3: switch on state per operation
  public void withdraw(double amt) {
    switch (state) {
      case InCredit:
        if (amt > bal) state = Overdrawn;
        bal -= amt;
        break;
      case Overdrawn:
      case Suspended:
        break;
    }
  }
}
โšก Entry / Exit Actions

ุงู„ู€ Entry action ุจุชุชู†ูุฐ ู„ู…ุง ุชุฏุฎู„ state. ูˆุงู„ู€ Exit action ู„ู…ุง ุชุฎุฑุฌ.

public void eventF() {  // transition INTO state S
  switch (state) {
    case T:
      doEntry();  // state T โ†’ S: trigger S's entry action
      state = S;
      break;
  }
}

public void eventG() {  // transition OUT of state S
  switch (state) {
    case S:
      doExit();   // state S โ†’ U: trigger S's exit action
      state = U;
      break;
  }
}
๐ŸŽฏ

Exam Bank โ€” Lecture 10

ุฃุณุฆู„ุฉ Code โ†” Class Diagram ู…ู† Fall 2021-22 ูˆ Winter 2021. ู‡ุงูŠ ููŠ ูƒู„ ุงู…ุชุญุงู† final.

Question 1 Fall 2021โ€“22 / Winter 2021 ยท Q1.07
Class diagram: Advertiser [1] โ”โ” [*] Account. Which code properly implements it?

(a) Advertiser has Set<Account> accounts. Account has single Advertiser owner. addAccount checks null + sets owner.
(b) Advertiser has single Account account field.
(c) Advertiser has Set; Account has Set<Advertiser> owners.
A Code (a)
B Code (b)
C Code (c)
โœ… ุงู„ุฅุฌุงุจุฉ ุงู„ุตุญ: A โ€” Code (a) ุงู„ู€ multiplicity 1:* ุจุชู‚ูˆู„: Advertiser ูˆุงุญุฏ โ†” Accounts ูƒุชูŠุฑุฉ. Code (a) ุตุญ:
  • Advertiser โ†’ Set<Account> accounts (collection).
  • Account โ†’ Advertiser owner (single reference).
  • addAccount + setOwner ู„ู„ุญูุงุธ ุนู„ู‰ bidirectional integrity.
B โ€” single field ุบู„ุทุ› Advertiser ุงู„ู…ูุฑูˆุถ ูŠุญู…ู„ multiple. ยท C โ€” Account has Set of Advertisers = many-to-manyุŒ ู…ุด 1-to-*.
Question 2 Fall 2021โ€“22 / Winter 2021 ยท Q1.08
Which class diagram represents this code?

class Order { OrderStatus status; ArrayList<OrderDetail> details; ... }
class OrderDetail { Product product; }
class Product { String code, name; float unitPrice; }
enum OrderStatus { OPEN, CLOSED; }
A Order โ—†[1:*] OrderDetail โ†’ Product (1:1); Order โ†’ OrderStatus enum
B Order [1:1] OrderDetail [1:1] Product
C Order โ†’ OrderDetail (plain association); โ†’ Product
D Order [*:*] OrderDetail many-to-many
โœ… ุงู„ุฅุฌุงุจุฉ ุงู„ุตุญ: A ArrayList<OrderDetail> = Order has many OrderDetails (multiplicity *). ูˆ Order owns OrderDetailsุŒ ูุงู„ุนู„ุงู‚ุฉ composition โ—†. ูƒู…ุงู† OrderDetail has 1 ProductุŒ ูˆ Order has OrderStatus enum.
Question 3 Practice โ€” operation contracts
What does an operation contract consist of?
A Just the method signature
B Preconditions + Postconditions
C Only the method body
D Class name + parent class
โœ… ุงู„ุฅุฌุงุจุฉ ุงู„ุตุญ: B โ€” Preconditions + Postconditions ุงู„ู€ contract ุจูŠูˆุตู ุงู„ู€ functionality ุจุดูƒู„ ุฑุณู…ูŠ: ุฅูŠู‡ ู„ุงุฒู… ูŠูƒูˆู† true ู‚ุจู„ ุงู„ุชู†ููŠุฐ (precondition)ุŒ ูˆุฅูŠู‡ ุงู„ู€ effect ุจุนุฏู‡ (postcondition).
Question 4 Practice โ€” multiplicity
UML: Manager [1] โ”โ†’ [*] Account. Best Java implementation?
A private Account account;
B private Manager mgr;
C private ArrayList<Account> accounts;
D private HashMap<String, Account> index;
โœ… ุงู„ุฅุฌุงุจุฉ ุงู„ุตุญ: C โ€” ArrayList Multiplicity * = many โ†’ collection (ArrayList/Set).
A โ€” single ref ูˆู…ุง ุจูŠู…ุซู„ุด many. ยท D โ€” HashMap ู„ู„ู€ qualified associations ูู‚ุท.
Question 5 Practice โ€” qualified
A qualified association in UML (e.g., Bank [accno] โ†’ Account) is best implemented with:
A ArrayList
B HashMap / HashTable
C Single reference field
D Stack
โœ… ุงู„ุฅุฌุงุจุฉ ุงู„ุตุญ: B โ€” HashMap ุงู„ู€ qualifier ู…ุนู…ูˆู„ ู„ู„ู€ efficient lookup. HashMap ุจูŠุฏูŠ O(1) lookup ุจุงู„ู€ key.
Question 6 Practice โ€” state diagram
What is the recommended way to implement a state diagram in code?
A One method for each transition
B Boolean field for each state
C Inheritance from a State class
D Define states as constants and use switch in each operation
โœ… ุงู„ุฅุฌุงุจุฉ ุงู„ุตุญ: D Steps: (1) constants for statesุŒ (2) initial state in constructorุŒ (3) switch ุญุณุจ ุงู„ู€ state ููŠ ูƒู„ operation.

(C) ู…ู…ูƒู† ูŠูุทุจู‚ ุจู€ State PatternุŒ ุฃู†ุธู ู„ูƒู† ุฃุนู‚ุฏ. ุงู„ุฏูƒุชูˆุฑ ุจูŠูˆุตูŠ ุจู€ (D) ู„ู„ุจุณุงุทุฉ.

Question 7 Practice โ€” order of impl
If you implement classes Top-Down, what is the main disadvantage?
A You need stubs for lower-level classes
B The system isn't testable until everything is done
C Higher classes are hard to design
D You lose object-orientation
โœ… ุงู„ุฅุฌุงุจุฉ ุงู„ุตุญ: A โ€” Stubs needed
Top-Down ูŠุจุฏุฃ ุจู€ high-level. ุงู„ู€ high-level methods ุจุชุนุชู…ุฏ ุนู„ู‰ lower classes โ†’ ู…ุญุชุงุฌ temporary stubs ู„ุชุฌุฑุจุชู‡ุง.
B โ€” ุฏูŠ ู…ูŠุฒุฉ ููŠ top-down: early validation. ยท D โ€” ู…ุด ู…ุชุนู„ู‚.
Question 8 Practice โ€” bidirectional
In a bidirectional 1:1 association between Account and Guarantor (both compulsory), what is the recommended creation order?
A Both at the same time using new (impossible in Java/C++)
B Random โ€” order doesn't matter
C Create one with default constructor, then create second pointing to it, then set reverse link
D Make them immutable singletons
โœ… ุงู„ุฅุฌุงุจุฉ ุงู„ุตุญ: C
Java doesn't allow simultaneous creation. ู„ุงุฒู… ุชุฎุงู„ู ุงู„ู€ constraint ู…ุคู‚ุชุงู‹: ุงุจุฏุฃ ุจู€ default GuarantorุŒ ุจุนุฏูŠู† Account(g)ุŒ ุจุนุฏูŠู† g.setAccount(a) โ€” ูƒุฏู‡ ุจุชูƒู…ู„ ุงู„ู€ bidirectional link.
๐Ÿ“‹

Cheat Sheet

UML โ†’ Code quick reference.

๐Ÿ”„ UML โ†’ Java Basics

Class
class X { }
Abstract
abstract class X
Interface
interface X
Enum
enum X { A, B }
Generalization
extends / implements
Attribute
field
Operation
method

๐Ÿ”ข Multiplicity โ†’ Code

1
single field + null check in constructor
0..1
single field (can be null)
*
ArrayList / Set
1..*
ArrayList + size check
{Immutable}
Explicit check in setter

๐Ÿ“ Special Patterns

Qualified
HashMap<Key, Object>
Association Class
Reified intermediate class
Many-to-many
Both have collections OR reify
Bidirectional
2 refs + delegate integrity to ONE class

๐Ÿ”„ State Diagram โ†’ Code

Step 1
Constants for states
Step 2
Initial in constructor
Step 3
switch(state) per operation
Composite
Group substates in same case
Entry/Exit
doEntry()/doExit() before state change
โšก

Rapid Revision

Flashcards ยท Common Mistakes.

3 implementation stepsุŸ
tap
Method interface ยท Order ยท Implement
Top-Down disadvantageุŸ
tap
Need stubs for lower classes
Multiplicity * โ†’ JavaุŸ
tap
ArrayList / Set / List
Qualified โ†’ JavaุŸ
tap
HashMap (O(1) lookup)
Bidirectional integrity solutionุŸ
tap
Delegate maintenance to ONE class
UML abstract โ†’ JavaุŸ
tap
abstract class
Operation contractุŸ
tap
Pre + Post conditions
State Diagram โ†’ ?
tap
constants + switch in operations

๐Ÿšจ Common Mistakes

1. ุฎู„ุท 1:* ุจู€ many-to-many1:* = ุทุฑู ุนู†ุฏู‡ collection ูˆุงู„ุทุฑู ุงู„ุชุงู†ูŠ ุนู†ุฏู‡ single ref. ุฃู…ุง m:n = ุงู„ุทุฑููŠู† ุนู†ุฏู‡ู… collections.
2. ู†ุณูŠุงู† referential integrityููŠ bidirectionalุŒ ู„ูˆ ุบูŠุฑุช reference ููŠ ุทุฑูุŒ ู„ุงุฒู… ุชุญุฏุซ ุงู„ู€ reference ููŠ ุงู„ุทุฑู ุงู„ุชุงู†ูŠ.
3. ุงุณุชุฎุฏุงู… HashMap ู„ู„ู€ * associationHashMap ู„ู„ู€ qualified ุจุณ. ุงู„ู€ * ุงู„ุนุงุฏูŠ ูŠุณุชุฎุฏู… ArrayList/Set.