Introduction to Object-Oriented Programming

Similar documents
Programming in the large

CS111: PROGRAMMING LANGUAGE II

Chapter 5 Object-Oriented Programming

Introduction to Object-Oriented Programming

CS111: PROGRAMMING LANGUAGE II

Lesson 14: Abstract Classes and Interfaces March 6, Object-Oriented S/W Development with Java CSCI 3381

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors

CS111: PROGRAMMING LANGUAGE II

Inheritance and object compatibility

Java Object Oriented Design. CSC207 Fall 2014

Chapter 7. Inheritance

Inheritance and Polymorphism

CS112 Lecture: Inheritance and Polymorphism

Inheritance. Inheritance Reserved word protected Reserved word super Overriding methods Class Hierarchies Reading for this lecture: L&L

COURSE 2 DESIGN PATTERNS

OOPS Viva Questions. Object is termed as an instance of a class, and it has its own state, behavior and identity.

Contents. I. Classes, Superclasses, and Subclasses. Topic 04 - Inheritance

OVERRIDING. 7/11/2015 Budditha Hettige 82

Lecture Contents CS313D: ADVANCED PROGRAMMING LANGUAGE. What is Inheritance?

CS 520 Theory and Practice of Software Engineering Fall 2018

ITI Introduction to Computing II

Object Oriented Programming: Based on slides from Skrien Chapter 2

CS313D: ADVANCED PROGRAMMING LANGUAGE

Classes and Inheritance Extending Classes, Chapter 5.2

CS5000: Foundations of Programming. Mingon Kang, PhD Computer Science, Kennesaw State University

ITI Introduction to Computing II

CPS122 Lecture: Encapsulation, Inheritance, and Polymorphism

Object Oriented Programming is a programming method that combines: Advantage of Object Oriented Programming

BBM 102 Introduction to Programming II Spring Abstract Classes and Interfaces

Object Oriented Design

Inheritance. OOP components. Another Example. Is a Vs Has a. Virtual Destructor rule. Virtual Functions 4/13/2017

Big software. code reuse: The practice of writing program code once and using it in many contexts.

Object-Oriented Concepts and Design Principles

CS 320 Introduction to Software Engineering Spring March 06, 2017

Inheritance, Polymorphism, and Interfaces

Day 4. COMP1006/1406 Summer M. Jason Hinek Carleton University

Outline. Subtype Polymorphism, Subtyping vs. Subclassing, Liskov Substitution Principle. Benefits of Subtype Polymorphism. Subtype Polymorphism

CS111: PROGRAMMING LANGUAGE II

9/10/2018 Programming Data Structures Inheritance

Announcement. Agenda 7/31/2008. Polymorphism, Dynamic Binding and Interface. The class will continue on Tuesday, 12 th August

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

Type Hierarchy. Lecture 6: OOP, autumn 2003

Java. Classes 3/3/2014. Summary: Chapters 1 to 10. Java (2)

n HW5 out, due Tuesday October 30 th n Part 1: Questions on material we ll cover today n Part 2: BFS using your graph from HW4

Intermediate Programming

Java Programming Lecture 7

Object-Oriented Programming: Polymorphism

CS-202 Introduction to Object Oriented Programming

index.pdf January 21,

STUDENT LESSON A20 Inheritance, Polymorphism, and Abstract Classes

BBM 102 Introduction to Programming II Spring 2017

Graphical Interface and Application (I3305) Semester: 1 Academic Year: 2017/2018 Dr Antoun Yaacoub

CS 215 Software Design Sample midterm solutions

Software Paradigms (Lesson 3) Object-Oriented Paradigm (2)

CS 520 Theory and Practice of Software Engineering Fall 2017

Software Engineering

Object-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018

OBJECT ORİENTATİON ENCAPSULATİON

[ L5P1] Object-Oriented Programming: Advanced Concepts

The software crisis. code reuse: The practice of writing program code once and using it in many contexts.

Object-Oriented Design

ITI Introduction to Computing II

ITI Introduction to Computing II

First IS-A Relationship: Inheritance

CS313D: ADVANCED PROGRAMMING LANGUAGE

What s Conformance? Conformance. Conformance and Class Invariants Question: Conformance and Overriding

HAS-A Relationship. If A uses B, then it is an aggregation, stating that B exists independently from A.

More Relationships Between Classes

Argument Passing All primitive data types (int etc.) are passed by value and all reference types (arrays, strings, objects) are used through refs.

Advanced Programming - JAVA Lecture 4 OOP Concepts in JAVA PART II

Module Contact: Dr Taoyang Wu, CMP Copyright of the University of East Anglia Version 1

CSC207 Week 3. Larry Zhang

More About Objects. Zheng-Liang Lu Java Programming 255 / 282

Software Development (cs2500)

HAS-A Relationship. Association is a relationship where all objects have their own lifecycle and there is no owner.

Java How to Program, 8/e

CMSC 132: Object-Oriented Programming II

ECE 122. Engineering Problem Solving with Java

Software Engineering /48

ob-ject: to feel distaste for something Webster's Dictionary

Originality is Overrated: OO Design Principles

Inheritance and Interfaces

OO Design Principles

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

PROGRAMMING LANGUAGE 2

Inheritance Motivation

Java and OOP. Part 3 Extending classes. OOP in Java : W. Milner 2005 : Slide 1

Inheritance. One class inherits from another if it describes a specialized subset of objects Terminology:

Lesson 10A OOP Fundamentals. By John B. Owen All rights reserved 2011, revised 2014

Example: Count of Points

CSCI-142 Exam 1 Review September 25, 2016 Presented by the RIT Computer Science Community

BBM 102 Introduction to Programming II Spring Inheritance

Object-Oriented Programming More Inheritance

Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Assoc. Prof. Marenglen Biba. (C) 2010 Pearson Education, Inc. All rights reserved.

The software crisis. code reuse: The practice of writing program code once and using it in many contexts.

More on Inheritance. Interfaces & Abstract Classes

Practice for Chapter 11

Exam Duration: 2hrs and 30min Software Design

Transcription:

Polymorphism 1 / 19

Introduction to Object-Oriented Programming Today we ll learn how to combine all the elements of object-oriented programming in the design of a program that handles a company payroll. Object-oriented programming requires three features: Data abstraction with classes (encapsulation) Inheritance Dynamic method binding That last part, dynamic method binding, provides for subtype polymorphism, which we ll learn today. 2 / 19

Class Hierarchies UML class hierarchies depict the superclass-subclass relationships between families of related classes. Employee SalariedEmployee HourlyEmployee Employee is the superclass of HourlyEmployee and SalariedEmployee Employee is more general than HourlyEmployee and SalariedEmployee, e.g., there at least as many Employee s as either HourlyEmployee s or SalariedEmployee s HourlyEmployee and SalariedEmployee are richer than Employee becuse they extend Employee with additional features 3 / 19

A SalariedEmployee Class Let s add SalariedEmployee to our class hierarchy. public final class SalariedEmployee3 extends Employee3 { private static final int MONTHS_PER_YEAR = 12; private final double annualsalary; public SalariedEmployee3(String aname, Date ahiredate, double anannualsalary) { super(aname, ahiredate); Disallowzeroesandnegatives(anAnnualSalary); annualsalary = anannualsalary; public double getannualsalary() { return annualsalary; public double monthlypay() { return annualsalary / MONTHS_PER_YEAR; //... 4 / 19

Our Employee Class Hierarchy We now have all the classes in our hierarchy: Employee SalariedEmployee HourlyEmployee But our classes aren t well factored. SalariedEmployee3 and HourlyEmployee3 have duplicate copies of disallowzeroesandnegatives SalariedEmployee3 and HourlyEmployee3 both have monthlypay methods, but these methods are not polymorphic because they re not defined in Employee3 Let s refactor our Employee class hierarchy to give it a clean object-oriented design. 5 / 19

A Company Spec Before we make monthlypay polymorphic, we need an application to demonstrate why doing so is useful. Let s design a Company class with the following specs: A Company4 has exactly 9 employees (because we haven t learned about dynamically resized data structures yet) A company calculates its monthly payroll by adding up the monthly pay of each of its employees. A company can have any mix of hourly and salaried employees That last bullet motivates the use of polymorphism. 6 / 19

Maintaining an Employee List With our current class hierarchy, we need to maintain separate (partial) arrays of hourly and salaried employees. Because they re partial arrays we also need to keep track of how many of each type of employee we have. public class Company { private HourlyEmployee[] hourlyemployees; private int numhourlyemployees = 10; private SalariedEmployee[] salariedemployees; private int numsalariedemployees = 10; public Company() { hourlyemployees = new HourlyEmployee[numHourlyEmployees]; salariedemployees = new SalariedEmployee[numSalariedEmployees]; 7 / 19

Calculating Payroll the Hard Way With our employee lists, calculating payroll is accomplished with two loops: public class Company { // hypothetical public double monthlypayroll() { double payroll = 0.0; for (int i = 0; i < numhourlyemployees; ++i) { payroll += hourlyemployees[i].monthlypay(); for (int i = 0; i < numsalariedemployees; ++i) { payroll += salariedemployees[i].monthlypay(); return payroll; //.. Seems reasonable. But... What if we want to add a third type of employee? 8 / 19

Calculating Payroll the Easy Way We d like to be able to calculate payroll with a single loop over all employees: public class Company4 { public double monthlypayroll() { double payroll = 0.0; for (Employee employee: employees) { payroll += employee.monthlypay(); return payroll; //.. Much cleaner and less error-prone (e.g., we don t have the book-keeping of two partial arrays). To be able to code like this we need to update the design of our Employee class hierarchy. 9 / 19

A More General Employee List The first step is to store one array of Employee s: public class Company4 { private Employee4[] employees; public Company4() { employees =...; public double monthlypayroll() { double payroll = 0.0; for (int i = 0; i < employees.length; ++i) { payroll += employees[i].monthlypay(); return payroll; Much better. But it doesn t compile. Why? $ javac Company.java Company.java:15: cannot find symbol symbol : method monthlypay() location: class Employee payroll += employees[i].monthlypay(); 10 / 19

Abstract Classes We need Employee to declare a monthlypay method for subclasses to define. Since we don t have a general definition for monthlypay suitable for Employee, Employee will need to be abstract. public abstract class Employee4 { //... public abstract double monthlypay(); An abstract class cannot be instantiated, may contain zero or more abstract methods, and subclasses must either provide an implementation for abstract methods, or be declared abstract themselves. This makes sense for our Employee4 class. We don t ever want to instantiate Employee4 objects. Employee4 simply defines the common aspects of all employees, with subclasses filling in the details. 11 / 19

The Employee4 Class Hierarchy Employee4 and its monthlypay method are abstract. monthlypay is polymorphic because it is overriden in subclasses. 12 / 19

Polymorphic Methods public class Company4 { private Employee4[] employees; public double monthlypayroll() { double payroll = 0.0; for (Employee4 employee: employees) { payroll += employees.monthlypay(); return payroll; The static type of the elements of employees is Employee4 The dynamic type can be any subclass of Employee4, in this case they are all SalariedEmployee4 and HourlyEmployee4 When a method is invoked on an object, the method of the dynamic (run-time) type is used, no matter what the static (compile-time) type is. So though the static types of employees elements is Employee, the monthlypay methods invoked on them are the ones defined in SalariedEmployee4 and HourlyEmployee4. 13 / 19

Refactoring Duplicate Code in a Class Hierarchy Recall the definition of disallowzeroesandnegatives: private void disallowzeroesandnegatives(double... args) { boolean shouldthrowexception = false; String nonpositives = ""; for (double arg: args) { if (arg <= 0.0) { shouldthrowexception = true; nonpositives += arg + " "; if (shouldthrowexception) { String msg = "Following arguments were <= 0: " + nonpositives; throw new IllegalArgumentException(msg); This method is duplicated in HourlyEmployee4 and SalariedEmployee4 Let s move the definition of disallowzeroesandnegatives into Employee5 so it will be shared (rather than duplicated) in SalariedEmployee5 and HourlyEmployee5. 14 / 19

protected Members private members of a superclass are effectively invisible to subclasses. To make a member accessible to subclasses, use protected: public abstract class Employee5 { protected void disallowzeroesandnegatives(double... args) { //... //... protected members are accessible to subclasses and other classes in the same package, and can be overriden in subclasses. protected members provide encapsulation within a class hierarchy and package, private provides encapsulation within a single class. Later we ll see a better way to re-use. 15 / 19

Implementation Inheritance Hinders Re-use Recall the disallowzeroesandnegatives method that we refactored so that it s in the Employee class and inherited by subclasses: public abstract class Employee6 { protected void disallowzeroesandnegatives(double... args) { //... There s nothing about this method that is specific to ~Employee~s disallowzeroesandnegatives could be useful in other classes that are not part of the Employee class hierarchy. Since it s protected, it can t be used outside of the Employee class hierarchy or package. In software engineering terms, we say that the code in Employee lacks cohesion - it has parts that aren t part of the Employee concept. Such a design hinders reuse. 16 / 19

Favor Composition over Inheritance If we move these protected methods into a separate class, like../code/employee/validationutils.java public class ValidationUtils { public static void disallownullarguments(object... args) {... public static void disallowzeroesandnegatives(double... args) {... we can use them anywhere, e.g., public Employee(String aname, Date ahiredate) { ValidationUtils.disallowNullArguments(aName, ahiredate); name = aname; hiredate = ahiredate; With this refactoring, we have our final versions of Employee.java, HourlyEmployee.java, and SalariedEmployee.java 17 / 19

Closing Thoughts on Polymorphism We ve now seen two kinds of polymorphism: Ad-hoc polymorphism (method overloading), and Subtype polymorphism (overriding methods in subtypes). Subtype polymorphism is core feature of OOP. Polymorphism makes it possible to reuse concepts in a way that makes programs extensible without requiring rewriting existing code - this is the open-closed principle. In the next block we ll see one more kind of polymorphism: type parameter polymorphism, or parametric polymorphism. 18 / 19

Object-oriented Design With encapsulation, inheritance, and polymorphism we have all the language features we need to employ three important object-oriented design principles: S ingle responsiblity principle: a module should only contain code related to the definition of the module Employee classes contain only employee-related code, validation code is in utility class O pen-closed principle: open for extension, closed for modification Can add new Employee subclasses without changing other classes in the Employee hierarchy or classes that use Employee~s, such as ~Company L liskov substitution principle: instances of subtypes should be substitutable wherever instances of supertypes are expected A square is not a rectangle in an OO sense, but both are 2-D shapes In CS 2340 you ll learn several more OO design principles and several patterns that employ them. 19 / 19