0% found this document useful (0 votes)
47 views29 pages

Lec5 CMPS242

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 29

CMPS 242

Object Oriented Programming


Spring 2022-2023

Dr. Julie BU DAHER


1
CMPS 242
Object Oriented Programming

Lecture 5 : UML and Classes Relationships

2
UML Diagrams
• UML stands for the Unified Modeling Language
• UML diagrams show relationships among classes and
objects
• A UML class diagram consists of one or more classes,
each with sections for the class name, attributes
(data), and operations (methods)
• Lines between classes represent associations
• A dotted arrow shows that one class uses the other
(calls its methods)
3
UML Representation of Class

Class Name

Attributes of Class

Methods of Class

4
Example of a Class Diagram
DVD Rental System
visibility multiplicity class name

Customer 1..* 1..*


DVD
-CID: int -DVD_ID : int
rents
-name: String -DVD_VolumeNo: int
+rentMovie()
+authenticateCustomer ()

attributes relationship methods


5
Visibility
of Attributes and Operations
Visibility Symbol Accessible To
Public + All objects within your system.

Protected # Instances of the class and its subclasses.

Private - Instances of the class only.

6
Example
Constant (final) Employee
field -name:String
(UPPERCASE) -payRate:double
-EMPLOYEE_ID:int
Static fields -nextID:int
(underlined) +STARTING_PAY_RATE:double
+Employee(String)
+Employee(String, double)
+getName():String
+getEmployeeID():int
+getPayRate():double
+changeName(String):void
+changePayRate(double):void
+getNextID():int

7
Corresponding Java Class
public class Employee {
private String name;
private double payRate;
private final int EMPLOYEE_ID;
private static int nextID = 1000;
public static final double STARTING_PAY_RATE = 7.75;
public Employee(String name) {
this.name = name;
EMPLOYEE_ID = getNextID();
payRate = STARTING_PAY_RATE;
}

public Employee(String name, double startingPay) {


this.name = name;
EMPLOYEE_ID = getNextID();
payRate = startingPay;
}
public String getName() { return name; }
public int getEmployeeID() { return EMPLOYEE_ID; }
public double getPayRate() { return payRate; }
public void changeName(String newName) { name = newName; }
public void changePayRate(double newRate) { payRate = newRate; }
public static int getNextID() {
int id = nextID;
nextID++;
return id;
}
8
}
The final Modifier
• The final variable is a constant:
final static double PI = 3.14159;
• The final class cannot be extended:
final class Math {
...
}
• The final method cannot be overridden by its
subclasses.

9
Object-Oriented Relationships
• Object oriented programs usually consists of a
number of classes
• Only one of these classes will have the main
method
• Classes have different relationships
• association defines a relationship between
classes of objects which allows one object
instance to cause another to perform an action
on its behalf
10
Class Relationships
• The most common relationships:
– Inheritance: A is-a B (discussed in details in Lecture 6)
– Association: A uses B
• Aggregation: A has-a B
• Composition: A part-of B

11
Inheritance: is-a relationship
• When creating a class, rather than declaring completely new members, the
programmer can designate that the new class inherits the members of an existing
class.
• The existing class is called the superclass, and the new class is the subclass.
• Inheritance allows the subclass to use the none private members of the super class
directly.
• A subclass normally adds its own fields and methods.
• The inheritance relation should be implemented only when is-a relationship is
clear and valid
class A{
int i;
int j; class Test{
void m1(){} public static void main (String [] arg){
class Loan{} } B b1=new B();
class B extends A{ b1.i=10;
class CarLoan extends Loan int k;
{} b1.m1();
void m2(){} }}
}
12
Inheritance: is-a relationship
• Each subclass can become the superclass for future
subclasses.
• Multiple inheritance is not allowed.
• In Java, the class hierarchy begins with class Object
which every class in Java directly or indirectly extends
(or "inherits from").

13
Association
• Association defines a relationship between classes of objects which allows
one object instance to cause another to perform an action on its behalf
• One way of implementation is by having object as a method argument

Customer purchase Book


A customer purchases a book

public class Customer


public class Book
{
{
….
private double price;
public void purchase(Book book)
{
public double getPrice()
book.getPrice();
{
//////
return price;
}
}
…..
}
}
14
Example Association by passing objects as arguments
public class Book{ public class Customer{
private double price; private double purchaseAmount;
private String title; public void purchase(Book book)
public Book(double price, {
String title) purchaseAmount +=book.getPrice();
{ }
this.price=price; public double getPurchaseAmount()
this.title=title; {
} return purchaseAmount ;
public double getPrice() } Main{
public class
{ } void main(String [] args){
public static
return price; Customer cutomer1=new Customer ();
} Book book1=new Book(100,”Java”);
public String getTitle() Book book2=new Book(200,“C#”);
{ cutomer1. purchase(book1);
cutomer1. purchase(book2);
return title; System.out.println(cutomer1.getPurchaseAmount());
} }
} }
15
15
Aggregation
• Aggregation is a type of association
• A connection between two objects where one
has a field that refers to the other.
• Aggregation is referred to as weak has a.
• has-a relationship is implemented by having
object as member variables

16
Aggregation Examples
“A person has a lawyer “

class Lawyer
class Person
{
{
public void
sue()

“A department has a }
}
professor“ public class Person{
private Lawyer lawyer; class Test
Person (Lawyer {
lawyer){ this.lawyer=lawyer; ….
} Lawyer mylawyer=new Lawyer ();
………. Person p1=new Person(myLawyer);
lawyer.sue() Person p2=new Person(myLawyer);
} }
17
Aggregation Between Same Class
Aggregation may exist between objects of the same class.
For example, a person may have a supervisor.

public class Person {


// The type for the data is the class itself
private Person supervisor;
...
}
18 18
Aggregation Between Same Class
What happens if a person has several supervisors?

public class Person {


...
private Person[] supervisors;
}

19 19
Composition
• A composition is a strong type of aggregation.
• Each component in a composite can belong to just one whole.
• Dependence relationship
• Composition defines the relation “owns a” / “part-of' relationship”/ strong has-a
• The lifetime of objects are associated, object of the part is created within owner.

The CoffeeTable owns 4Leg


A house owns a room

public class Test


public class Car{ {
Engine e; public static void main (String []
public Car(){ arg)
public class Engine {
{…. e=new Engine();
} Car car1 =new Car();
} }
}
} 20
Composition vs Aggregation
• Composition is a special case of aggregation relationship
(more restricted form)
• In aggregation, objects exist independently within the
scope of the system
• In composition, objects cannot exist independently
within the scope of the system
– Aggregation -> independency
– Composition -> dependency
Composition Aggregation

1 1 1..3 1
Name Student Address

21 21
Aggregation Example
• In the following example, a Student object is
composed, in part, of Address objects
• A student has an address (in fact each student
has two addresses)
• See StudentBody.java
• See Student.java
• See Address.java

22
Aggregation in UML
StudentBody Student
- firstName : String
+ main (args : String[]) : void - lastName : String
- homeAddress : Address
- schoolAddress : Address

+ toString() : String
Address
- streetAddress : String
- city : String
- state : String
- zipCode : long

+ toString() : String

23
//********************************************************************
// Represents a street address.
//********************************************************************

public class Address


{
private String streetAddress, city, state;
private long zipCode;

//---------------------------------------------------------------
// Constructor: Sets up this address with the specified data.
//---------------------------------------------------------------
public Address(String street, String town, String st, long zip)
{
streetAddress = street;
city = town;
state = st;
zipCode = zip;
}

continue

24
continue

//-------------------------------------------------------
// Returns a description of this Address object.
//-------------------------------------------------------
public String toString()
{
String result;

result = streetAddress + "\n";


result += city + ", " + state + " " + zipCode;

return result;
}
}

25
public class Student
{
private String firstName, lastName;
private Address homeAddress, schoolAddress;

//-----------------------------------------------------------------
// Constructor: Sets up this student with the specified values.
//-----------------------------------------------------------------
public Student(String first, String last, Address home,
Address school)
{
firstName = first;
lastName = last;
homeAddress = home;
schoolAddress = school;
}

continue

26
continue

//-------------------------------------------------------
// Returns a string description of this Student object.
//-------------------------------------------------------
public String toString()
{
String result;

result = firstName + " " + lastName + "\n";


result += "Home Address:\n" + homeAddress + "\n";
result += "School Address:\n" + schoolAddress;

return result;
}
}

27
public class StudentBody
{
//-----------------------------------------------------------------
// Creates some Address and Student objects and prints them.
//-----------------------------------------------------------------
public static void main(String[] args)
{
Address school = new Address("800 Lancaster Ave.", "Villanova",
"PA", 19085);
Address jHome = new Address("21 Jump Street", "Lynchburg",
"VA", 24551);
Student john = new Student("John", "Smith", jHome, school);

Address mHome = new Address("123 Main Street", "Euclid", "OH",


44132);
Student marsha = new Student("Marsha", "Jones", mHome, school);

System.out.println(john);
System.out.println();
System.out.println(marsha);
}
}

28
Output
//********************************************************************
// StudentBody.java Author: Lewis/Loftus
// John Smith
// Demonstrates the use of an
Home aggregate class.
Address:
//********************************************************************
21 Jump Street
Lynchburg, VA 24551
public class StudentBody
{ School Address:
800 Lancaster Ave.
//-----------------------------------------------------------------
Villanova,
// Creates some Address PA 19085
and Student objects and prints them.
//-----------------------------------------------------------------
public static void main (String[]
Marsha Jones args)
{
Home Address:
Address school = new Address ("800 Lancaster Ave.", "Villanova",
123 Main Street
"PA", 19085);
Euclid, OH 44132
Address jHome = new Address ("21 Jump Street", "Lynchburg",
School Address:
"VA", 24551);
800
Student john = new Lancaster
Student Ave.
("John", "Smith", jHome, school);
Villanova, PA 19085
Address mHome = new Address ("123 Main Street", "Euclid", "OH",
44132);
Student marsha = new Student("Marsha", "Jones", mHome, school);

System.out.println(john);
System.out.println();
System.out.println(marsha);
}
}
29

You might also like