CS 112 Introduction to Programming Object Relationship Analysis: Composition, Association, Inheritance Yang (Richard) Yang Computer Science Department.

Slides:



Advertisements
Similar presentations
CS 112 Introduction to Programming
Advertisements

Class Hierarchy (Inheritance)
Inheritance Inheritance Reserved word protected Reserved word super
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 8.1 – 8.5.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 9: Inheritance and Interfaces.
Aalborg Media Lab 23-Jun-15 Inheritance Lecture 10 Chapter 8.
CS 106 Introduction to Computer Science I 11 / 19 / 2007 Instructor: Michael Eckmann.
1 Inheritance Readings: Writing classes Write an Employee class with methods that return values for the following properties of employees at a.
Unit 011 Inheritance Recall What Inheritance is About The extends Keyword The Object Class Overriding versus Overloading What is Actually Inherited? Single.
Chapter 10: Inheritance 1. Inheritance  Inheritance allows a software developer to derive a new class from an existing one  The existing class is called.
(c) University of Washington03-1 CSC 143 Java Inheritance Reading: Ch. 10.
Copyright 2008 by Pearson Education Building Java Programs Chapter 9 Lecture 9-1: Inheritance reading:
Copyright 2010 by Pearson Education Topic 31 - inheritance.
CS 112 Introduction to Programming Inheritance Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:
1 Java Inheritance. 2 Inheritance On the surface, inheritance is a code re-use issue. –we can extend code that is already written in a manageable manner.
Polymorphism, Inheritance Pt. 1 COMP 401, Fall 2014 Lecture 7 9/9/2014.
1 Given the Radio class  We may define other derivative types: Cassette walkman IS-A radio Alarm clock radio IS-A radio Car radio IS-A radio.
CSC 142 Computer Science II Zhen Jiang West Chester University
Copyright 2008 by Pearson Education Building Java Programs Chapter 8 Lecture 19: encapsulation, inheritance reading: (Slides adapted from Stuart.
CS 112 Introduction to Programming Inheritance Hierarchy; Polymorphism Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone:
Checking Equality of Reference Variables. Arrays and objects are both “reference” types n They are allocated a chunk of memory in the address space n.
Copyright 2008 by Pearson Education Building Java Programs Chapter 9 Lecture 9-1: Inheritance reading:
Some Object-Oriented Programming (OOP) Review. Let’s practice writing some classes Write an Employee class with methods that return values for the following.
1 final (the keyword, not the exam). 2 Motivation Suppose we’ve defined an Employee class, and we don’t want someone to come along and muck it up  E.g.,
MIT AITI 2004 – Lecture 12 Inheritance. What is Inheritance?  In the real world: We inherit traits from our mother and father. We also inherit traits.
CS 112 Introduction to Programming Design Good Classes: Encapsulation and OOP Analysis Yang (Richard) Yang Computer Science Department Yale University.
1 Building Java Programs Chapter 9: Inheritance and Interfaces These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They may not be.
Outline Creating Subclasses Overriding Methods Class Hierarchies Visibility Designing for Inheritance Inheritance and GUIs The Timer Class Copyright ©
Inheritance Inheritance allows a programmer to derive a new class from an existing one The existing class is called the super class, or parent class,
Programming Abstractions Cynthia Lee CS106X. Inheritance Topics Inheritance  The basics › Example: Stanford GObject class  Polymorphism › Example: Expression.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
1 Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L 9.1 – 9.4.
Copyright 2010 by Pearson Education Building Java Programs Chapter 9 Lecture 9-1: Inheritance reading: 9.1.
Inheritance Type/Subtype Relationship. Inheritance Idea: An object B of one type, termed child class, inherits from another object A of another type,
CET203 SOFTWARE DEVELOPMENT Session 2A Inheritance (programming in C#)
Java Inheritance in Java. Inheritance Inheritance is a mechanism in which one object acquires all the properties and behaviors of parent object. The idea.
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
Copyright 2008 by Pearson Education Building Java Programs Chapter 9: Inheritance and Interfaces Lecture 9-1.
CS 112 Introduction to Programming Nested Loops; Parameterized Methods Yang (Richard) Yang Computer Science Department Yale University 208A Watson, Phone:
Copyright 2009 by Pearson Education Building Java Programs Chapter 9: Inheritance and Interfaces Lecture 9-1.
CS 112 Introduction to Programming Java Graphics Yang (Richard) Yang Computer Science Department Yale University 208A Watson, Phone:
CS 112 Introduction to Programming Design Good Classes: Visualization and OOP Analysis Yang (Richard) Yang Computer Science Department Yale University.
Programming Abstractions Cynthia Lee CS106B. Inheritance Topics Inheritance  The basics › Example: Stanford GObject class  Polymorphism.
CS 112 Introduction to Programming Class Inheritance Yang (Richard) Yang Computer Science Department Yale University 208A Watson, Phone:
CS 112 Introduction to Programming Method Overriding; Object Hierarchy; Event-Driven Programming Yang (Richard) Yang Computer Science Department Yale University.
Building Java Programs Chapter 9
Building Java Programs Chapter 9
The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs. Large-scale projects face.
Lecture 15: More Inheritance
Inheritance Inheritance allows a programmer to derive a new class from an existing one The existing class is called the super class, or parent class,
Lecture 9-2: Interacting with the Superclass (super);
Week 8 Lecture -3 Inheritance and Polymorphism
Adapted from slides by Marty Stepp and Stuart Reges
The software crisis software engineering: The practice of developing, designing, documenting, testing large computer programs. Large-scale projects face.
Building Java Programs
Building Java Programs
Law firm employee analogy
Lecture 14: Inheritance Building Java Programs: A Back to Basics Approach by Stuart Reges and Marty Stepp Copyright (c) Pearson All rights reserved.
Building Java Programs
Topic 31 - inheritance.
Building Java Programs
Inheritance Readings: 9.1.
Lecture 15: Inheritance II
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Building Java Programs
Presentation transcript:

CS 112 Introduction to Programming Object Relationship Analysis: Composition, Association, Inheritance Yang (Richard) Yang Computer Science Department Yale University 208A Watson, Phone:

2 Admin  Project next step

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 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 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

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.

Domain of Visualization based on Geography

Example Use Cases  RandomColorMap.java  RedBlueMap.java  ClickColorMap.java  GeoMap.java

Domain of Visualization based on Geography Classes and their relationships?

10 Major Classes and Relationship GeoMapRegion Polygon Color Point 1mm2 111m A composition relationship An association relationship

11 Major Classes and Relationship GeoMap Region String … Polygon Color Point …

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?

 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 Major Classes and Relationship GeoMapRegion Polygon Color Point 1mm2 111m A composition relationship An association relationship Discussion: -Public methods (API) of Point

15 Major Classes and Relationship GeoMapRegion Polygon Color Point 1mm2 111m A composition relationship An association relationship Discussion: -Public methods (API) of Polygon

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 Major Classes and Relationship GeoMapRegion Polygon Color Point 1mm2 111m A composition relationship An association relationship Discussion: -Public methods (API) of Region

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.

Example Controllers  GeoMap.java  RandomColorMap.java  ClickColorMap.java  RedBlueMap.java

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

Cartograms  Cartogram. Area of state proportional to number of electoral votes. Michael Gastner, Cosma Shalizi, and Mark Newman www-personal.umich.edu/~mejn/election

Cartograms  Cartogram. Area of country proportional to population.

23 Outline  Admin and recap  Defining classes  Object-oriented design o Geo-map visualization and has/associate relationship  Class inheritance

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

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 Major Classes and Relationship StaffEmployee A composition relationship Secretary 1m m LegalSec Marketer Lawyer m m m

An Employee class public class Employee { public int hours() { return 40; // works 40 hours / week } public double pay() { return ; // $50, / 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

Question: Writing class Secretary  Secretaries are employees who can prepare documents. 28

Secretary class: Attempt 1 public class Secretary { public int hours() { return 40; // works 40 hours / week } public double pay() { return ; // $50, / 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

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

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 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 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 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() {…}; }

Exercise: Implement Secretary 35

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