Download presentation
Presentation is loading. Please wait.
Published byMarybeth Davis Modified over 8 years ago
1
CS 112 Introduction to Programming Object Relationship Analysis: Composition, Association, Inheritance Yang (Richard) Yang Computer Science Department Yale University 208A Watson, Phone: 432-6400 Email: yry@cs.yale.edu
2
2 Admin Project next step
3
Recap: Math.random() and Random Objects r Random generator must be stateful and hence is natural to use objects r Design lesson: One can implement static Math.random() using singleton and delegation. 3 public class Math { private static Random rand; public static double random() { if (rand == null) rand = new Random(); return rand.nextDouble(); }.. } A static variable, also called a singleton. A delegation implementation pattern.
4
4 Recap: Complex Number Objects r Design lesson: we design behaviors of complex numbers to be consistent with those of standard numbers (complex numbers are numbers after all): immutable objects public Complex plus(Complex b) { double real = re + b.re; double imag = im + b.im; return new Complex(real, imag); }
5
5 Outline Admin and recap Defining classes o Motivation and basic syntax o Simple examples o The encapsulation principle o Object examples o DrawingPanel objects vs StdDraw o Random objects vs Math.random o Complex number objects and fractal graphics Object-oriented design Geo-map visualization and has/associate relationship
6
Data Visualization “ If I can't picture it, I can't understand it. ” — Albert Einstein 6 Edward Tufte. Create charts with high data density that tell the truth.
7
Domain of Visualization based on Geography
8
Example Use Cases RandomColorMap.java RedBlueMap.java ClickColorMap.java GeoMap.java
9
Domain of Visualization based on Geography Classes and their relationships?
10
10 Major Classes and Relationship GeoMapRegion Polygon Color Point 1mm2 111m A composition relationship An association relationship
11
11 Major Classes and Relationship GeoMap Region String … Polygon Color Point …
12
12 Major Classes and Relationship GeoMapRegion Polygon Color Point 1mm2 111m A composition relationship An association relationship Design question: - What is the basic controller structure?
13
Retrieve region (standard) m Batch: retrieve list of all regions m Specific: retrieve one specific region Coloring (customized) m Map properties of each region to a color 13 Coloring Controller Structure
14
14 Major Classes and Relationship GeoMapRegion Polygon Color Point 1mm2 111m A composition relationship An association relationship Discussion: -Public methods (API) of Point
15
15 Major Classes and Relationship GeoMapRegion Polygon Color Point 1mm2 111m A composition relationship An association relationship Discussion: -Public methods (API) of Polygon
16
Polygon public class Polygon { private final int N; // number of boundary points private final Point[] points; // the points // read from input stream public Polygon(Scanner input) { N = input.nextInt(); points = new Point[N+1]; for (int i = 0; i < N; i++) { points[i] = new Point ( input ); } points[N] = points[0]; } … public void draw() { … } public void fill() { … } public boolean contains(Point p) { … } public Point centroid() { … } … }
17
17 Major Classes and Relationship GeoMapRegion Polygon Color Point 1mm2 111m A composition relationship An association relationship Discussion: -Public methods (API) of Region
18
Region public class Region { private final String regionName; // name of region private final String mapName; private final Polygon poly; // polygonal boundary private Color fillColor, drawColor; public Region(String mName, String rName, Polygon poly) { regionName = rName; mapName = mName; this.poly = poly; setDefaultColor(); } public void setDrawColor (Color c) { drawColor = c; } public void draw() { setDrawColor(); poly.draw (); } public void fill() { … } public boolean contains(Point p) { return poly.contains(p); } public Point centroid() { return poly.centroid() } … } Q: Should Region have a method that returns its internal Polygon? Even though most complexity is in Polygon, Polygon is not exposed. Region delegates tasks internally to Polygon.
19
Example Controllers GeoMap.java RandomColorMap.java ClickColorMap.java RedBlueMap.java
20
Extension: Purple America (PurpleMap.java) Idea. [Robert J. Vanderbei] Assign color based on number of votes. m a 1 = Rep. votes. m a 2 = Other votes. m a 3 = Dem. votes. 100% Dem 100% Rep 100% Other 55% Dem, 45% Rep public Color getColor() { int dem = tally.dem(), rep = tally.rep(), ind = tally.ind(); int tot = tally.dem + tally.rep + tally.ind; return new Color((float) rep/tot, (float) ind/tot, (float) dem/tot); } PurpleAmerica.java
21
Cartograms Cartogram. Area of state proportional to number of electoral votes. Michael Gastner, Cosma Shalizi, and Mark Newman www-personal.umich.edu/~mejn/election
22
Cartograms Cartogram. Area of country proportional to population.
23
23 Outline Admin and recap Defining classes Object-oriented design o Geo-map visualization and has/associate relationship Class inheritance
24
A Law Firm Problem: Setting The firm has 5 types of employees m Standard employee m Secretary knows how to prepare ordinary documents m Legal secretary knows how to prepare both ordinary documents and legal documents. m Marketer knows how to advertise m Lawyer knows how to sue 24
25
A Law Firm Problem: Policies m Work time policy: Employees work 40 hours / week. m Pay policy: Employees make a base salary of $50,000 per year, except that o legal secretaries make 10% extra over base per year, o marketers make 20% extra over base per year, o lawyers who reach partner level get bonus. m Vacation policy: Employees have 2 weeks of paid vacation leave per year, except that o lawyers get an extra week on top of base, o employees should use a yellow form to apply for leave, except for lawyers who use a pink form. 25 Classes and their relationships?
26
26 Major Classes and Relationship StaffEmployee A composition relationship Secretary 1m m LegalSec Marketer Lawyer m m m
27
An Employee class public class Employee { public int hours() { return 40; // works 40 hours / week } public double pay() { return 50000.0; // $50,000.00 / year } public int vacationDays() { return 10; // 2 weeks' paid vacation } public String vacationForm() { return "yellow"; // use the yellow form } public String toString() { String result = "Hours: " + hours() + "\n"; result += "Pay: " + pay() + "\n"; result += "Vacation days: " + vacationDays() + "\n"; result += "Vacation Form: " + vacationForm() + "\n"; return result; } 27
28
Question: Writing class Secretary Secretaries are employees who can prepare documents. 28
29
Secretary class: Attempt 1 public class Secretary { public int hours() { return 40; // works 40 hours / week } public double pay() { return 50000.0; // $50,000.00 / year } public int vacationDays() { return 10; // 2 weeks' paid vacation } public String vacationForm() { return "yellow"; // use the yellow form } public String toString() { String result += "Hours: " + hours() + "\n"; result += "Pay: ” + pay() + "\n"; result += "Vacation days: " + vacationDays() + "\n"; result += "Vacation Form: " + vacationForm() + "\n"; return result; } public void prepareDoc(String text) { System.out.println(“Working on Document: " + text); } } 29
30
Desire for code-sharing prepareDoc is the only unique behavior in Secretary. We'd like to be able to say: // A class to represent secretaries. public class Secretary { public void prepareDoc(String text) { System.out.println(“Work on Document: " + text); } 30
31
Inheritance Inheritance: A way to allow a software developer to reuse classes by deriving a new class from an existing one m The existing class is called the parent class, or superclass, or base class m The derived class is called the child class or subclass. As the name implies, the child inherits characteristics of the parent m The child class inherits every method and every data field defined for the parent class 31
32
32 Inheritance Inheritance relationships are often shown graphically in a class diagram, with the arrow pointing to the parent class Inheritance should create an is-a relationship, meaning the child is a more specific version of the parent Animal - weight : int + getWeight() : int Bird + fly() : void - flySpeed : int
33
33 Inheritance The child class inherits all methods and data defined for the parent class Animal - weight : int + getWeight() : int Bird - flySpeed : int + fly() : void weight = 120 getWeight() weight = 100 flySpeed = 30 getWeight() fly() an animal object a bird object
34
34 Deriving Subclasses: Syntax public class extends { } For example: class Animal { // class contents private int weight; public int getWeight() {…} } class Bird extends Animal { private int flySpeed; public void fly() {…}; }
35
Exercise: Implement Secretary 35
36
Summary: Improved Secretary code // A class to represent secretaries. public class Secretary extends Employee { public void prepareDoc(String text) { System.out.println(“Working on document: " + text); } } By extending Employee, each Secretary object now: receives methods hours, pay, vacationDays, vacationForm, toString from Employee ’s definition automatically can be treated as an Employee by client code (seen later) Now we only write the parts unique to each type. 36
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.