+ All Categories
Home > Documents > CS 112 Introduction to Programming Inheritance Yang (Richard) Yang Computer Science Department Yale...

CS 112 Introduction to Programming Inheritance Yang (Richard) Yang Computer Science Department Yale...

Date post: 27-Dec-2015
Category:
Upload: adele-floyd
View: 216 times
Download: 1 times
Share this document with a friend
Popular Tags:
48
CS 112 Introduction to Programming Inheritance Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: [email protected]
Transcript
Page 1: CS 112 Introduction to Programming Inheritance Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu.

CS 112 Introduction to Programming

Inheritance

Yang (Richard) YangComputer Science Department

Yale University308A Watson, Phone: 432-6400

Email: [email protected]

Page 2: CS 112 Introduction to Programming Inheritance Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu.

2

Admin

Class project

Page 3: CS 112 Introduction to Programming Inheritance Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu.

3

Recap: OOP Analysis

GeoMap Region

Polygon

Color

Point

1 m m 2

1

1

1

m

A composition relationship An association

relationship

Page 4: CS 112 Introduction to Programming Inheritance Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu.

Retrieve region Batch: retrieve list of all regions Specific: retrieve one specific region

Coloring Map properties of a region to a color

4

Recap: OOP Analysis: Controller Structure

Page 5: CS 112 Introduction to Programming Inheritance Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu.

Encapsulation is a key problem solving technique for large, complex problems

A good way to learn more is to read about designs of large-scale OOP software systems

Recap: OOP Analysis

Page 6: CS 112 Introduction to Programming Inheritance Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu.

6

Software Design and Reuse

Question: What programming language feature(s) have we covered to allow software reuse?

Page 7: CS 112 Introduction to Programming Inheritance Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu.

7

Outline

Admin and recap Class inheritance

o why and how?

Page 8: CS 112 Introduction to Programming Inheritance Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu.

A Law Firm Problem: Setting

Consider the following law firm: Work time policy: Employees work 40 hours / week. Pay policy: Employees make a base salary of $50,000 per

year, except thato 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.

Vacation policy: Employees have 2 weeks of paid vacation leave per year, except thato 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.

8

Page 9: CS 112 Introduction to Programming Inheritance Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu.

A Law Firm Problem: Setting

Each type of employee has some job functions:Lawyers know how to sue.Marketers know how to advertise.Secretaries know how to prepare ordinary documents.Legal secretaries know how to prepare both ordinary

documents and legal documents.

9

Page 10: CS 112 Introduction to Programming Inheritance Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu.

An Employee classpublic 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; }}

10

Page 11: CS 112 Introduction to Programming Inheritance Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu.

Question: Writing class Secretary

Secretaries are employees who can prepare documents.

11

Page 12: CS 112 Introduction to Programming Inheritance Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu.

Secretary class: Attempt 1public 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); }} 12

Page 13: CS 112 Introduction to Programming Inheritance Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu.

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 { <copy all the contents from the Employee class>

public void prepareDoc(String text) { System.out.println(“Work on Document: " + text); }}

13

Page 14: CS 112 Introduction to Programming Inheritance Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu.

Inheritance

Inheritance: A way to allow a software developer to reuse classes by deriving a new class from an existing one

The existing class is called the parent class, or superclass, or base class

The derived class is called the child class or subclass.

As the name implies, the child inherits characteristics of the parent

The child class inherits every method and every data field defined for the parent class

14

Page 15: CS 112 Introduction to Programming Inheritance Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu.

15

Inheritance

Inheritance relationships are often shown graphically in a class diagram, with the arrow pointing to the parent class

Inheritance should Inheritance should create an create an is-a is-a relationshiprelationship, , meaning the child meaning the child is ais a more specific more specific version of the version of the parentparent

Animal- weight : int

+ getWeight() : int

Bird

+ fly() : void

- flySpeed : int

Page 16: CS 112 Introduction to Programming Inheritance Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu.

16

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 = 120getWeight()

weight = 100flySpeed = 30 getWeight()fly()

an animal object

a bird object

Page 17: CS 112 Introduction to Programming Inheritance Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu.

17

Deriving Subclasses: Syntax

public class <name> extends <superclass> {

}

For example:

class Animal { // class contents

private int weight; public int getWeight() {…}

}

class Bird extends Animal { private int flySpeed;

public void fly() {…};}

Page 18: CS 112 Introduction to Programming Inheritance Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu.

Exercise: Implement Secretary

18

Page 19: CS 112 Introduction to Programming Inheritance Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu.

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.

19

Page 20: CS 112 Introduction to Programming Inheritance Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu.

20

Outline

Admin and recap Class inheritance

o why and how?o inheritance and object construction

Page 21: CS 112 Introduction to Programming Inheritance Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu.

21

Inheritance and Constructor

When constructing an object, Java makes sure that the constructor of the parent is first called If no parent constructor called, Java

automatically inserts super() as the first statement in the constructor of a child class:

public class Secretary extends Employee { public Secretary () { // super() is automatically inserted System.out.println(“In Secretary()”); }

…}

Page 22: CS 112 Introduction to Programming Inheritance Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu.

Example

22

public class Secretary extends Employee { public Secretary() { // super() is automatically inserted System.out.println(“In Secretary()”); } …}

public class Employee { public Employee() { System.out.println(“In Employee()”); } …}

public static void main(String[] args) { Secretary seth = new Secretary();}

In Employee()In Secretary()

Output:

Page 23: CS 112 Introduction to Programming Inheritance Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu.

Exercise: Add Name to Employeepublic class Employee { private String name;

public Employee(String name) { this.name = name; }

…}

23

Page 24: CS 112 Introduction to Programming Inheritance Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu.

Problem with constructors

Now that we've added the constructor to the Employee class, our subclasses do not compile.

The short explanation: Once we write a constructor (that requires parameters) in the superclass, we must now write constructors for our employee subclasses as well.

The long explanation: (next couple slides)

Page 25: CS 112 Introduction to Programming Inheritance Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu.

25

The explanation

Constructors aren't inherited. The Employee subclasses don't inherit the public Employee(String name) constructor.

After defining public Employee(String), Java sees that we have a constructor, and will no longer provide the default Employee constructor. i.e., public Employee() is not defined unless we

define it explicitly

But public Secretary() {

// super() is automatically inserted but not defined // in Employee System.out.println(“In Secretary()”);

}

Page 26: CS 112 Introduction to Programming Inheritance Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu.

26

super and Constructor

If you insert super(…)as the first statement in child’s constructor, Java will not insert the default parent constructor:

public class Secretary extends Employee { public Secretary(String name) { super(name); System.out.println(“In Secretary()”); } …}

public class Employee { private String name; public Employee(String name) { System.out.println(“In Employee()”); this.name = name; } …}

Page 27: CS 112 Introduction to Programming Inheritance Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu.

Example: Picture Type

Raster graphics. Basis for image processing. Set of values. 2D array of Color objects (pixels).

API.

Page 28: CS 112 Introduction to Programming Inheritance Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu.

Exercise: Extending the Picture Type

Although the Picture class is quite useful already, it misses some useful filtering functions such as grayScale, scaling

Goal: create a new type InstaPic with all of the existing methods defined in Picture, with two additional methods: gray and scale

28

Page 29: CS 112 Introduction to Programming Inheritance Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu.

Monochrome Luminance

Monochrome luminance. Effective brightness of a color (NTSC formula):

Y = 0.299r + 0.587g + 0.114b.

import java.awt.Color;

public class Luminance {

public static double lum(Color c) { int r = c.getRed(); int g = c.getGreen(); int b = c.getBlue(); return .299*r + .587*g + .114*b; }

}

Page 30: CS 112 Introduction to Programming Inheritance Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu.

Grayscale Filter

mandrill.jpg

Page 31: CS 112 Introduction to Programming Inheritance Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu.

Color Compatibility

Q. Which font colors will be most readable with which background colors on computer and cell phone screens?

A. Rule of thumb: difference in luminance should be 128.

public static boolean compatible(Color a, Color b) { return Math.abs(lum(a) - lum(b)) >= 128.0;}

208255 28 14105 47

Page 32: CS 112 Introduction to Programming Inheritance Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu.

Scaling Filter

mandrill.jpg(298-by-298)

Page 33: CS 112 Introduction to Programming Inheritance Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu.

Image Scaling

Goal. Shrink or enlarge an image to desired size.

Assume uniform strategy to convert from ws-by-hs to wt -by-ht :

?

source image(ws-by-hs)

target image(wt-by-ht)

y (x,y)y hs / ht)(x ws / wt,

Page 34: CS 112 Introduction to Programming Inheritance Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu.

Scaling Filter

Scaling filter. Creates two Picture objects and two windows.

% java Scale mandrill.jpg 400 200mandrill.jpg(298-by-298)

Page 35: CS 112 Introduction to Programming Inheritance Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu.

Back to Law Firm: Implementing the Lawyer class: Attempt 1// A class to represent lawyers.public class Lawyer extends Employee {

public void sue() { System.out.println("I'll see you in court!"); }

}

35

Page 36: CS 112 Introduction to Programming Inheritance Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu.

Problem

We want lawyers to inherit most behaviors from employee, but we want to replace parts with new behavior:o Lawyers get an extra week of paid vacation

over base vacation (a total of 3).o Lawyers use a pink form when applying for

vacation leave.

36

Page 37: CS 112 Introduction to Programming Inheritance Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu.

37

Defining Methods in the Child Class: Overriding Methods

A child class can (have the option to) override the definition of an inherited method in favor of its own that is, a child can redefine a method that it

inherits from its parent the new method must have the same

signature as the parent's method, but can have different code in the body

The method invoked is always the one defined in the child class, if the child class refines (overrides) a method

Page 38: CS 112 Introduction to Programming Inheritance Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu.

Lawyer class

// A class to represent lawyers.public class Lawyer extends Employee {

// overrides getVacationDays from Employee class public int vacationDays() { return 15; // 3 weeks vacation }

// overrides getVacationForm from Employee class public String vacationForm() { return "pink"; } public void sue() { System.out.println("I'll see you in court!"); }}

38

Page 39: CS 112 Introduction to Programming Inheritance Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu.

39

Overloading vs. Overriding

Overloading deals with multiple methods in the same class with the same name but different signatures

Overloading lets you define a similar operation in different ways for different data

Overriding deals with two methods, one in a parent class and one in a child class, that have the same signature

Overriding lets you define a similar operation in different ways for different object types

Page 40: CS 112 Introduction to Programming Inheritance Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu.

Marketer class

– Exercise: Complete the Marketer class. Marketers can advertise and make 20% more than the base ($60,000 total).

40

Page 41: CS 112 Introduction to Programming Inheritance Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu.

Marketer class

// A class to represent marketers.public class Marketer extends Employee { public void advertise() { System.out.println("Act while supplies last!"); }

// override public double pay() { return 60000.0; // $60,000.00 / year }}

41Problem of design?

Page 42: CS 112 Introduction to Programming Inheritance Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu.

A Problem

public class Marketer extends Employee { public double pay() { return 60000.0; } ...}

Problem: The Marketer‘s salaries are based on the Employee’s base salary (20% more than base), but the pay code does not reflect this.

42

Page 43: CS 112 Introduction to Programming Inheritance Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu.

Changes to Common Behavior Imagine a company-wide change affecting all

employees.

Example: Everyone is given a $10,000 raise due to inflation.The base employee salary is now $60,000.Marketers should now make $72,000.

We must modify our code to reflect this policy change.

43

Page 44: CS 112 Introduction to Programming Inheritance Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu.

Modifying the superclass

// A class to represent employees in general (20-page manual).public class Employee { public int hours() { return 40; // works 40 hours / week }

public double pay() { return 60000.0; // $60,000.00 / year }

...}

Issue: the Marketer subclass is still incorrect. It has overridden pay to return another value.

Requirement: derived behavior is based on base behavior

44

Page 45: CS 112 Introduction to Programming Inheritance Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu.

Calling overridden methods

Subclasses can call overridden methods with super

super.<method>(<parameters>)

– Exercise: Modify Marketer to derive pay for marketers from base pay.

45

Page 46: CS 112 Introduction to Programming Inheritance Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu.

Improved subclasses

public class Marketer extends Employee { public void advertise() { System.out.println("Act now while supplies last!"); }

// override and invoke the parent’s version public double pay() { return super.pay() * 1.2; }}

46

Page 47: CS 112 Introduction to Programming Inheritance Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu.

Exercise: Revise Lawyer to Maintain Consistency

47

Page 48: CS 112 Introduction to Programming Inheritance Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu.

Solution

public class Lawyer extends Employee { public String vacationForm() { return "pink"; } public int vacationDays() { return super.vacationDays() + 5; } public void sue() { System.out.println("I'll see you in court!"); }}

48


Recommended