Admin. q Admin and recap q Class inheritance

Similar documents
CS 112 Introduction to Programming

What is Polymorphism? CS 112 Introduction to Programming

Admin. CS 112 Introduction to Programming. Recap: OOP Analysis. Software Design and Reuse. Recap: OOP Analysis. Inheritance

CS 112 Introduction to Programming. (Spring 2012)

Admin. CS 112 Introduction to Programming. Admin. Admin. Recap. Recap: Polymorphism and Arrays. the Google doc to record the teaming

CS 112 Introduction to Programming

Building Java Programs

AP Computer Science. Interactions with superclass

Topic 32 - Polymorphism

Inheritance. Writing classes. Writing more classes. Why are they very similar? Employee class. Secretary class. Readings: 9.1

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

Lecture 15: Inheritance II

ADTs, Interfaces, Inheritance & Polymorphism

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

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

CS 112 Introduction to Programming

Topic 31 - inheritance

COMPUTER SCIENCE DEPARTMENT PICNIC. Operations. Push the power button and hold. Once the light begins blinking, enter the room code

Programming in C# Inheritance and Polymorphism

BBM 102 Introduction to Programming II

Object Oriented Features. Inheritance. Inheritance. CS257 Computer Science I Kevin Sahr, PhD. Lecture 10: Inheritance

CS 112 Introduction to Programming

CS 112 Introduction to Programming

Admin. CS 112 Introduction to Programming. Recap: The Critter Class. Recap: Event-Driven Programming. State Machine Driven Cougar.

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

Polymorphism. Polymorphism is an object-oriented concept that allows us to create versatile software designs

ECE 122. Engineering Problem Solving with Java

BBM 102 Introduction to Programming II Spring 2017

Inheritance -- Introduction

File: D:\My Documents\Classes\Computer Science\Class Notes\Fall New\Polymorphism\Employee.java 7/20/1999, 10:53:52 AM

CS111: PROGRAMMING LANGUAGE II

OVERRIDING. 7/11/2015 Budditha Hettige 82

Review of Object-Oriented Concepts in JAVA

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

Polymorphism. Agenda

Relationships Between Real Things CSE 143. Common Relationship Patterns. Employee. Supervisor

Inheritance. Inheritance allows the following two changes in derived class: 1. add new members; 2. override existing (in base class) methods.

Relationships Between Real Things. CSE 143 Java. Common Relationship Patterns. Composition: "has a" CSE143 Sp Student.

Java Object Oriented Design. CSC207 Fall 2014

Relationships Between Real Things CSC 143. Common Relationship Patterns. Composition: "has a" CSC Employee. Supervisor

AP Computer Science. Gridworld, inheritance

Object Orientated Programming Details COMP360

Chapter 6 Reflection

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

Programming Abstractions

Software and Programming 1

Inheritance and Polymorphism

Inheritance Chapter 8. Instructor: Scott Kristjanson CMPT 125/125 SFU Burnaby, Fall 2013

Programming II (CS300)

Abstract Classes and Interfaces

A base class (superclass or parent class) defines some generic behavior. A derived class (subclass or child class) can extend the base class.

CS 106B Lecture 27: Inheritance and Polymorphism in C++

C08: Inheritance and Polymorphism

What is Inheritance?

ECE 122. Engineering Problem Solving with Java

Inheritance and Polymorphism

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

drawobject Circle draw

Binghamton University. CS-140 Fall Dynamic Types

CS111: PROGRAMMING LANGUAGE II

Classes and Inheritance Extending Classes, Chapter 5.2

Inheritance. Transitivity

CLASS DESIGN. Objectives MODULE 4

Name Return type Argument list. Then the new method is said to override the old one. So, what is the objective of subclass?

1- Differentiate between extends and implements keywords in java? 2- What is wrong with this code:

About 1. Chapter 1: Getting started with oop 2. Remarks 2. Examples 2. Introduction 2. OOP Introduction 2. Intoduction 2. OOP Terminology 3.

Super-Classes and sub-classes

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

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

Java Magistère BFA

Chapter 7. Inheritance

11/19/2014. Inheritance. Chapter 7: Inheritance. Inheritance. Inheritance. Java Software Solutions for AP* Computer Science A 2nd Edition

Inheritance. = way of forming new classes based on existing ones = way to share/reuse codebetween two or more classes

CS313D: ADVANCED PROGRAMMING LANGUAGE

CmSc 150 Fundamentals of Computing I. Lesson 28: Introduction to Classes and Objects in Java. 1. Classes and Objects

Inheritance and Polymorphism. CS180 Fall 2007

Inheritance (Part 5) Odds and ends

C08: Inheritance and Polymorphism

Overview. Lecture 7: Inheritance and GUIs. Inheritance. Example 9/30/2008

Polymorphism. Final Exam. November 26, Method Overloading. Quick Review of Last Lecture. Overriding Methods.

Class Hierarchy and Interfaces. David Greenstein Monta Vista High School

Computer Science II (20073) Week 1: Review and Inheritance

Computer Science 210: Data Structures

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

Programming Abstractions

CS 106X Lecture 26: Inheritance and Polymorphism in C++

Arrays Classes & Methods, Inheritance

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

COSC 121: Computer Programming II. Dr. Bowen Hui University of Bri?sh Columbia Okanagan

Java Inheritance. Classes implement the concept of ADT:

Programming II (CS300)

CS-202 Introduction to Object Oriented Programming

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

INHERITANCE. Spring 2019

Inheritance. Unit 8. Summary. 8.1 Inheritance. 8.2 Inheritance: example. Inheritance Overriding of methods and polymorphism The class Object

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

ENCAPSULATION AND POLYMORPHISM

1.00 Lecture 13. Inheritance

8. Polymorphism and Inheritance

Module Contact: Dr Geoff McKeown, CMP Copyright of the University of East Anglia Version 1

Transcription:

Admin CS 112 Introduction to Programming q Class project Please work on forming teams Inheritance Hierarchy; Polymorphism Yang (Richard) Yang Computer Science Department Yale University 308A Watson, Phone: 432-6400 Email: yry@cs.yale.edu 2 Recap: Inheritance Example Extension q Inheritance: A way to allow a software developer to reuse classes by deriving a new class from an existing one, e.g., Secretary extends Employee InstaPic extends Picture q When constructing an object, Java makes sure that the constructor of the parent is first called insertion of super() if no super() as first statement in a constructor slight complexity: Java adds a default constructor for each class, if the class has no constructor q Overriding methods allow a child class to revise the behaviors of the parent class q The boss wants to give employees more vacation days the longer they've been with the firm: For each year worked, award 2 additional vacation days. When an Employee object is constructed, we'll pass in the number of years the person has been with the firm. Exercise: Make necessary modifications to the Employee class. q Design principle: when overriding parent s behavior, derive behavior (e.g., 1.2 times base pay), not the final outcome (e.g., $60,000) 3 4 Solution: Add Served Years to Employee Outline private String name; private int years; public Employee(String name, int years) { this.name = name; this.years = years; public Employee(String name) { this.name = name; years = 0; public int vacationdays () { return 10 + 2 * years; // 0 year service as default q Admin and recap q Class inheritance o why and how? o inheritance and object construction o overriding and using overridden methods o inheritance and field access 5 6 1

Inheritance and Fields q Setting: To retain the best lawyers, the firm will pay a lawyer the base and $5000 for each year in the firm public class Lawyer extends Employee { public double pay() { return super.pay() + 5000 * years; Problem q Fields declared private cannot be accessed from subclasses Reason: so that subclassing cannot break encapsulation Q: how to get around this limitation? https://encrypted-tbn0.gstatic.com/images?q=tbn:and9gcr3inpyvkdurlozvetxxw0yyttzi1b5uo0pd8_jkodow0iipy9a 7 8 Solution 1 Solution 2 q Java provides a third visibility modifier to denote fields/methods to be accessible by only child classes: protected q Add an accessor for any field needed by the subclass private String name; private int years; public Employee(String name, int initialyears) { this.name = name; years = initialyears; private String name; protect int years; public Employee(String name, int years) { this.name = name; this.years = years; public int getyears() { return years;... public class Lawyer extends Employee { public Lawyer(String name, int years) { super(name, years); 9 public double pay() { return super.pay() + 5000 * getyears();... 10 Discussion Outline q Which design do you like? Design 1: make year protected Design 2: Add public getyear() q Settings where protected is more appropriate than adding a public accessor? Adding public getyear() makes it available to not only child class, but also all other classes q Admin and recap q Class inheritance o why and how? o inheritance and object construction o overriding and using overridden methods o inheritance and field access o inheritance hierarchy 11 12 2

Levels of inheritance Multiple levels of inheritance in a hierarchy are allowed. Example: A legal secretary is the same as a regular secretary but makes more money (10% more) and can file legal briefs. Exercise: Implement the LegalSecretary class. LegalSecretary class // A class to represent legal secretaries. public class LegalSecretary extends Secretary { public void filelegalbriefs() { System.out.println("I could file all day!"); public double pay() { return super.pay() * 1.1 ; 13 14 Partner class q Partner is a senior lawyer that can get bonus. Thus it supports: awardbonus(double bonus) Partner class // A class to represent partner. public class Partner extends Lawyer { private double bonus; public void awardbonus(double bonus) { this.bonus = bonus; public double pay() { return super.pay() + bonus ; 15 16 Class Hierarchies q Many large-scale software systems define class hierarchies, where the root defines the common behaviors Class Hierarchies: Another Example Animal Employee Reptile Bird Mammal Secretary Lawyer Marketer Snake Lizard Parrot Horse Bat LegalSecretary Partner 17 18 3

The Object Class The Object Class: the tostring Method q A class called Object is defined in the java.lang package of the Java standard class library q All classes in Java are derived from the Object class even if a class is not explicitly defined to be the child of an existing class, it is assumed to be the child of the Object class the Object class is therefore the ultimate root of all class hierarchies q The Object class contains a few most basic methods, which are inherited by all classes tostring() equals() clone() q The tostring method in the Object class is defined to return a string that contains the name of the object s class and a hash value q Every time we have defined tostring, we have actually been overriding it q Shortcut: If the parameter to the println method is an object, the method will invoke the tostring method 19 20 Outline q Admin and recap q Class inheritance o why and how? o inheritance and object construction o overriding and using overridden methods o inheritance and field access o inheritance hierarchy o inheritance and method binding Example Setting q It turns out that the vacation bonus policy does not apply to secretaries: they get fixed 10 days vacation, not (10 + 2 * years) 21 22 Solution 1 q We set all Secretaries to 0 years of service because they do not have vacation bonus public class Secretary extends Employee { public Secretary(String name, int years) { super(name, 0); public void preparedoc(string text) { System.out.println( Working on doc + text); Problem q Solution 1 is not good: If we call getyears() on a Secretary object, we get 0 What if we wanted to give other rewards to all employees based on years of service? 23 24 4

Idea: Separation private String name; private int years; public int vacationdays () { return 10 + 2 * years; Separate base days and bonus days to allow adaptation Improved Employee code q Separate the standard 10 vacation days from those that are awarded based on seniority. private int years; public Employee(int initialyears) { years = initialyears; public int getvacationdays() { return 10 + getseniorityvacation(); // vacation days given for each year in the company return 2 * years;... How does this help us improve the Secretary? 25 Improved Secretary code q Secretary can override getseniorityvacation. public class Secretary extends Employee { public Secretary(String name, int years) { super(name, years); // Secretaries don't get a bonus for their years of service. return 0; public void preparedoc(string text) { System.out.println( Working on text: " + text); Example Client public class Firm { public static void main(string args) { Secretary seth = new Secretary( Seth, 10); int vacdays = seth.getvacationdays(); public int getvacationdays() { return 10 + getseniorityvacation(); return 2 * years; Secretary obj s method // Defined in class Secretary return 0; Example Client public class Firm { public static void main(string args) { Lawyer larry = new Lawyer( Larry, 10); int vacdays = larry.getvacationdays(); public int getvacationdays() { return 10 + getseniorityvacation(); return 2 * years; Summary q The method invoked is always determined by the object, not the class. q Hence when a method in a base class invokes the name of another method defined in the base class, the real method invoked can be defined either in the base class, or a child class. public int getvacationdays() { return 10 + getseniorityvacation(); q This is called dynamic binding. 5

Outline What is Polymorphism? q Admin and recap q Class inheritance o why and how? o inheritance and object construction o overriding and using overridden methods o inheritance and field access o inheritance hierarchy o inheritance and polymorphism q polymorphism: Ability for the same code to be used with different types of objects and behave differently with each. 31 Recap: Reference Variables Recap: Object Reference Variable q Interaction with an object occurs through object reference variables q An object reference variable holds the reference (address, the location) of an object ChessPiece bishop1 = new ChessPiece(); q Object reference variable assignment copies address, creating aliases bishop1 Before bishop2 = bishop1; bishop2 bishop1 After bishop2 bishop1 33 34 Polymorphic Reference through Inheritance q A variable of type T can hold an object of class T or descendent of T, e.g., Employee emp = new Employee( Ed ); emp = new Lawyer( Larry ); emp = new LegalSecretary( Lisa ); q When we use a variable v of type T to refer to objects both of base type T and descent of T, we say that it is a polymorphic reference through inheritance Polymorphic Reference and Method q You can call any methods defined in the based class T (e.g., Employee) class on polymorphic reference of type T (e.g., emp) q When you invoke a method through a polymorphic reference variable, it is the type of the object being referenced, not the reference type, that determines which method is invoked. q Careful use of polymorphic references can lead to elegant, robust software designs 6

Polymorphic Reference through Inheritance Polymorphic Reference: Example Reference variable type Employee ed ed.vacationdays() // 15 ed.vacationdays() // 10 Object type: Lawyer Object type: Secretary Employee emp; emp = new Lawyer("Larry"); System.out.println ( emp.vacationdays() ); // OUTPUT: 15 System.out.println ( emp.vacationform() ); // OUTPUT: pink emp = new LegalSecretary( Lisa"); System.out.println ( emp.vacationdays() ); // OUTPUT: 10 System.out.println ( emp.vacationform() ); // OUTPUT: yellow 37 38 Polymorphic Method Parameter q Define a method that takes a reference to a base type and apply to all derived types. q This is how print in PrintStream is defined: void print(object obj) { // all objects have the tostring() method // convert to string and then output Polymorphic Method Parameter: Example public class EmployeeMain { public static void main(string[] args) { Lawyer lisa = new Lawyer(); Secretary steve = new Secretary(); printinfo(lisa); printinfo(steve); public static void printinfo(employee empl) { System.out.println("salary: " + empl.pay()); System.out.println("v.days: " + empl.vacationdays()); System.out.println("v.form: " + empl.vacationform()); System.out.println(); OUTPUT: salary: 50000.0 salary: 50000.0 v.days: 15 v.days: 10 v.form: pink v.form: yellow Polymorphism and Arrays Polymorphism and Arrays: Example q A common usage of polymorphism is to define an array of a base type, but different entries refer to different types of objects To handle a heterogeneous population of objects with uniformity public class Staff { private Employee[] stafflist; public Staff() { stafflist = new Employee[4]; stafflist[0] = new Lawyer("Lisa"); stafflist[1] = new Secretary("Sally"); stafflist[2] = new Marketer("Mike"); stafflist[3] = new LegalSecretary("Lynne"); Works on any mix of Employee objects public void payday() { for (int count = 0; count < stafflist.length; count++) { System.out.printf("%-10s:", stafflist[count].name()); System.out.printf("$%.2f\n", stafflist[count].pay()); System.out.println("-----------------------------------"); 7

Exercise: Extending the Program: Hourly q Include a new type of secretary who are paid by hours. 43 8