Classes: Relationships Among Objects. Atul Prakash Background readings: Chapters 8-11 (Downey)



Similar documents
Inheritance, overloading and overriding

LINKED DATA STRUCTURES

You are to simulate the process by making a record of the balls chosen, in the sequence in which they are chosen. Typical output for a run would be:

Java CPD (I) Frans Coenen Department of Computer Science

Introduction to Object-Oriented Programming

CS1002: COMPUTER SCIENCE OO MODELLING & DESIGN: WEEK 5

Arrays. Atul Prakash Readings: Chapter 10, Downey Sun s Java tutorial on Arrays:

1) Which of the following is a constant, according to Java naming conventions? a. PI b. Test c. x d. radius

Entity Relationship Diagram

Software Engineering Techniques

CSE 308. Coding Conventions. Reference

6.088 Intro to C/C++ Day 4: Object-oriented programming in C++ Eunsuk Kang and Jean Yang

Software Engineering Concepts: Testing. Pointers & Dynamic Allocation. CS 311 Data Structures and Algorithms Lecture Slides Monday, September 14, 2009

Outline. Computer Science 331. Stack ADT. Definition of a Stack ADT. Stacks. Parenthesis Matching. Mike Jacobson


IMDB Data Set Topics: Parsing Input using Scanner class. Atul Prakash

Basics of Java Programming Input and the Scanner class

Linked Lists Linked Lists, Queues, and Stacks

More on Objects and Classes

CS170 Lab 11 Abstract Data Types & Objects

LAB4 Making Classes and Objects

3 Pillars of Object-oriented Programming. Industrial Programming Systems Programming & Scripting. Extending the Example.

Item 7: Prefer Immutable Atomic Value Types

Intruduction to Groovy & Grails programming languages beyond Java

Introduction: Abstract Data Types and Java Review

LAB 1. Familiarization of Rational Rose Environment And UML for small Java Application Development

1. INTRODUCTION TO RDBMS

This explanations are for absolute beginners. Skilled programmers should (and probably will) use more effective approach.

Data Structures Using C++ 2E. Chapter 5 Linked Lists

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

Licensed for viewing only. Printing is prohibited. For hard copies, please purchase from

Graduate Assessment Test (Sample)

Course: Programming II - Abstract Data Types. The ADT Queue. (Bobby, Joe, Sue, Ellen) Add(Ellen) Delete( ) The ADT Queues Slide Number 1

Java is an Object-Oriented Language. As a language that has the Object Oriented feature, Java supports the following fundamental concepts:

The following program is aiming to extract from a simple text file an analysis of the content such as:

Database Design and Normalization

7.1 Our Current Model

An Introduction To UML Class Diagrams Classes

Project 4 DB A Simple database program

Exercise 1: Relational Model

Object-Oriented Programming in Java

First Java Programs. V. Paúl Pauca. CSC 111D Fall, Department of Computer Science Wake Forest University. Introduction to Computer Science

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

Chapter 14 The Binary Search Tree

SSC - Communication and Networking Java Socket Programming (II)

WA2099 Introduction to Java using RAD 8.0 EVALUATION ONLY. Student Labs. Web Age Solutions Inc.

JAVA - OBJECT & CLASSES

An Incomplete C++ Primer. University of Wyoming MA 5310

The C Programming Language course syllabus associate level

ProTrack: A Simple Provenance-tracking Filesystem

AP Computer Science Static Methods, Strings, User Input

Getting Started with the Internet Communications Engine

Advanced Java Client API

CS193j, Stanford Handout #10 OOP 3

Programming by Contract. Programming by Contract: Motivation. Programming by Contract: Preconditions and Postconditions

Creating Database Tables in Microsoft SQL Server

Database Design Basics

INTRODUCTION TO COMPUTER PROGRAMMING. Richard Pierse. Class 7: Object-Oriented Programming. Introduction

Object-Oriented Programming Lecture 2: Classes and Objects

Semantic Analysis: Types and Type Checking

JAVA ARRAY EXAMPLE PDF

Consuming a Web Service(SOAP and RESTful) in Java. Cheat Sheet For Consuming Services in Java

WEB SERVICES TECHNICAL GUIDE FOR DEVELOPERS

Object-Oriented Programming in Java

The Entity-Relationship Model

Loops and ArrayLists

Install Java Development Kit (JDK) 1.8

BSc (Hons) Business Information Systems, BSc (Hons) Computer Science with Network Security. & BSc. (Hons.) Software Engineering

Java Classes. GEEN163 Introduction to Computer Programming

Building a Multi-Threaded Web Server

The Java Series. Java Essentials I What is Java? Basic Language Constructs. Java Essentials I. What is Java?. Basic Language Constructs Slide 1

<Insert Picture Here> What's New in NetBeans IDE 7.2

Quiz 4 Solutions EECS 211: FUNDAMENTALS OF COMPUTER PROGRAMMING II. 1 Q u i z 4 S o l u t i o n s

Introduction to Java Applications Pearson Education, Inc. All rights reserved.

Automatic generation of fully-executable code from the Domain tier of UML diagrams

Lecture J - Exceptions

Algorithms and Data Structures Written Exam Proposed SOLUTION

Creating a 2D Game Engine for Android OS. Introduction

Java Cheatsheet. Tim Coppieters Laure Philips Elisa Gonzalez Boix

CMSC 202H. ArrayList, Multidimensional Arrays

El Dorado Union High School District Educational Services

Chulalongkorn University International School of Engineering Department of Computer Engineering Computer Programming Lab.

File class in Java. Scanner reminder. Files 10/19/2012. File Input and Output (Savitch, Chapter 10)

Database Applications Recitation 10. Project 3: CMUQFlix CMUQ s Movies Recommendation System

To Java SE 8, and Beyond (Plan B)

Using ilove SharePoint Web Services Workflow Action

SE 360 Advances in Software Development Object Oriented Development in Java. Polymorphism. Dr. Senem Kumova Metin

OTN Developer Day Enterprise Java. Hands on Lab Manual JPA 2.0 and Object Relational Mapping Basics

AP Computer Science A 2011 Free-Response Questions

How To Run A Test File Extension On A Rexx (Unix) On A Microsoft Linux (Amd64) (Orchestra) (For Windows) (

Masters programmes in Computer Science and Information Systems. Object-Oriented Design and Programming. Sample module entry test xxth December 2013

Write Barrier Removal by Static Analysis

CS 2112 Spring Instructions. Assignment 3 Data Structures and Web Filtering. 0.1 Grading. 0.2 Partners. 0.3 Restrictions

Free Java textbook available online. Introduction to the Java programming language. Compilation. A simple java program

Java: overview by example

Transcription:

Classes: Relationships Among Objects Atul Prakash Background readings: Chapters 8-11 (Downey)

Real-World Relationships: Parent-child relationships among members of a species Friends relationship among users on Facebook Students who part of the same team City-city relationship for a flight network In the above cases, two objects of the same class have a relationship with each other

Multiple Classes A program will often use multiple classes E.g.: for handling data in IMDB, classes could be Movie, Actor, User, Review, Ratings,... In Java, each class will be in its own.java file: Movie.java, Actor.java, User.java, Review.java, Ratings.java, etc.

Relationships among objects from multiple classes Classes: Student, Course, Professor, Classroom Student <-> Course Professor <-> Course Course <-> Classroom Classes: Movie, Actor, User, Review Movie <-> Actor User <-> Review Movie <-> Review

Types of Relationships One-to-one: Patient <-> Patient Record One-to-many or many-to-one: Person (Mom) <-> Person (child) A mom can have 1 or more children Many-to-many: Student <-> Course A student can take many courses A course can be taken by many students

One-to-one relationships One-to-one relation among objects A and B One way to represent it both ways: A contains a reference to B B contains a reference to A Patient A pr PatientRecords B p

Example Patient and PatientRecord public class Patient { private String name; private String socialsecuritnumber; private PatientRecords pr; public class PatientRecords { private String doctor; private Patient p; public Patient(String name, String s) { this.name = name; this.socialsecuritnumber = s; pr = null; public void setpatientrecords(patientrecords r) { this.pr = r; public PatientRecords(String doctor) { this.doctor = doctor; p = null; public void setpatient(patient p) { this.p = p;

One-to-many relations Use an array or a list. For now, we will use an array, so we get practice with them, though lists are a better choice Person a Item[] myitems; Person owner; Person owner; Item x Item y int numitems; Person owner; Item z myitems contains [x, y, z, null, null,...] numitems is 3 owner for x, y, and z contains a

Initializing an array Initialize in the constructor myitems = new Item[MAXITEMS]; Creates an empty array of pointers to items Each pointer is initialized to empty, indicated by a value of null by Java.

Using an array to store Operations: adding an item owned removing an owned item: no longer owned The array will contain the items owned, but which slots contain the items? items One design: Maintain the following invariants Slots containing the items are at the beginning of the array Unused slots at the end Good: [x, y, z, *, *, *], numitems = 3 Bad: [*, x, *, y, z, *], numitems = 3 * is don t care. Good to set it to null.

Adding an item Simply add at the end items[numitems] = newitem; Why it works? Because of the invariant on the last slide Initial: [x, y, z, *, *, *], numitems = 3 Adding w results in: [x,y, z, w, *], numitems = 4

Removing an item The item being removed can be anywhere in the array Need to find it first by scanning the array Then, to maintain the invariant, you need to shift the following elements to the left by 1 Finally, decrement numitems Initial: [x, y, z, *, *, *], numitems = 3 To delete y, first find its position, which is 1. Deleting with k = 1 results in Final: [x,z, *, *, *], numitems = 2

Shifting elements Example: deleting item at position k for (int i = k; i < size-1; i++) { items[i] = items[i+1]; numitems--; // IMPORTANT. Re-establish invariant items[numitems] = null; // OPTIONAL. Good to do so. Initial: [x, y, z, *, *, *], numitems = 3 Deleting with k = 1 results in [x,z, *, *, *], numitems = 2

Creating Relationships One way: create records, link them public class Main { public static void main(string[] args) { Patient a = new Patient("Joe", "123-45-6789"); PatientRecords b = new PatientRecords("dr. evans"); a.setpatientrecords(b); // patient has a link to its record b.setpatient(a); // record has a link to its patient Patient a pr PatientRecords b p

Problem Desired invariant: two-way relationship Should not be possible for a user of these two classes to violate the above. Unfortunately, it is possible to do so. Patient a = new Patient(...); PatientRecords b = new PatientRecords("dr. evans"); a.setpatientrecords(b); // patient has a link to its record // no link created from b to a

Better Solution The method that adds one relationship also adds the opposite relationship. PatientRecords code Patient code public void setpatient(patient patient) { if (patient!= p) { this.p = patient; patient.setpatientrecords(this); public void setpatientrecords(patientrecords r) { if (r!= pr) { this.pr = r; r.setpatient(this); Invariant is maintained irrespective of whether setpatient or setpatientrecords is called

Question Why are the if checks important? What happens if you omit them? PatientRecords code Patient code public void setpatient(patient patient) { if (patient!= p) { this.p = patient; patient.setpatientrecords(this); public void setpatientrecords(patientrecords r) { if (r!= pr) { this.pr = r; r.setpatient(this);

Another Example Class: Student Relationship: students can team up. A student can be in the same team as another student. One solution: Each student objects contains a list or array containing its team members Student[] teammembers;

Reflect on the Design Information in the current design is duplicated If 4 students are in a team, they have basically the same list. Updates must occur in 4 objects S1 S2 S3 S4 Can we avoid duplication? Right now, we need to remember to update in multiple places to maintain the team invariant

Solution Introduce another class to hold the relationship A Student object can contain a link to its Team object Team T1 maintains list of students A Team object that contains links to all the team members in one array S1 S2 S3 S4 Now, the list of team members is in one place. Updates are easier

What did we do? When information is duplicated in multiple objects, consolidate it one object Have all the objects share a single copy of that object by maintaining a link to it This is called introducing indirection. Rather than storing the information directly in multiple places, store it once and refer to it indirectly via a link

Summary Objects can have relationships among themselves Use pointers or links for that Enforce invariants if links are bi-directional Avoid data duplication. If information is duplicated in multiple places, introduce an additional class to hold the data in one place Existing objects point to the object from new class