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

Similar documents
Topic 31 - inheritance

Topic 32 - Polymorphism

Building Java Programs

BBM 102 Introduction to Programming II

BBM 102 Introduction to Programming II Spring 2017

AP Computer Science. Gridworld, inheritance

AP Computer Science. Interactions with superclass

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

Lecture 15: Inheritance II

ADTs, Interfaces, Inheritance & Polymorphism

CS 112 Introduction to Programming

Admin. q Admin and recap q Class inheritance

What is Polymorphism? CS 112 Introduction to Programming

CS 112 Introduction to Programming

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.

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

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

CS 112 Introduction to Programming. (Spring 2012)

Practice Problems: Inheritance & Polymorphism

CS 112 Introduction to Programming. (Spring 2012)

Practice Problems: Inheritance & Polymorphism

CS 112 Introduction to Programming. Final Review. Topic: Static/Instance Methods/Variables: I am confused

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

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

CSE 143 Lecture 12 Inheritance

Practice Problems: Inheritance & Polymorphism

Programming Abstractions

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

Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object.

CS111: PROGRAMMING LANGUAGE II

Building Java Programs. Inheritance and Polymorphism

Programming Abstractions

Arrays Classes & Methods, Inheritance

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

CS313D: ADVANCED PROGRAMMING LANGUAGE

Inheritance and Interfaces

AP CS Unit 6: Inheritance Notes

Software and Programming 1

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

OVERRIDING. 7/11/2015 Budditha Hettige 82

Programming Exercise 14: Inheritance and Polymorphism

Inheritance (Part 5) Odds and ends

CS107 Handout 37 Spring 2007 May 25, 2007 Introduction to Inheritance

Programming Abstractions

Binghamton University. CS-140 Fall Dynamic Types

Abstract Classes. Abstract Classes a and Interfaces. Class Shape Hierarchy. Problem AND Requirements. Abstract Classes.

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

CS313D: ADVANCED PROGRAMMING LANGUAGE

Object-Oriented Programming (Java)

University of British Columbia CPSC 111, Intro to Computation 2009W2: Jan-Apr 2010 Tamara Munzner

Object Orientated Programming Details COMP360

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

CSc 110, Spring 2017 Lecture 37: Critters. Adapted from slides by Marty Stepp and Stuart Reges

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

Inheritance. Transitivity

Reusing Classes. Hendrik Speleers

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

CS111: PROGRAMMING LANGUAGE II

Inheritance and Polymorphism

University of British Columbia CPSC 111, Intro to Computation Jan-Apr 2006 Tamara Munzner

1.00 Lecture 13. Inheritance

WEEK 13 EXAMPLES: POLYMORPHISM

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

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

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

Chapter 5. Inheritance

BSc. (Hons.) Software Engineering. Examinations for / Semester 2

C++ Important Questions with Answers

Method Overriding in Java

Sorting. Sorting. Selection sort

CSC207H: Software Design. Java + OOP. CSC207 Winter 2018

drawobject Circle draw

Classes and Inheritance Extending Classes, Chapter 5.2

ECE 122. Engineering Problem Solving with Java

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

Superclasses / subclasses Inheritance in Java Overriding methods Abstract classes and methods Final classes and methods

Inheritance Motivation

COMP 110/L Lecture 19. Kyle Dewey

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

The class Object. Lecture CS1122 Summer 2008

More on Inheritance. Interfaces & Abstract Classes

Programming overview

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

Introduction to OOP with Java. Instructor: AbuKhleif, Mohammad Noor Sep 2017

Inheritance and Polymorphism

Object-Oriented Programming

COE318 Lecture Notes Week 8 (Oct 24, 2011)

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

Rules and syntax for inheritance. The boring stuff

Java Object Oriented Design. CSC207 Fall 2014

Accelerating Information Technology Innovation

Computer Science 210: Data Structures

CLASS DESIGN. Objectives MODULE 4

Inheritance (Outsource: )

Object-Oriented ProgrammingInheritance & Polymorphism

CS 11 java track: lecture 3

Section: Inheritance Heck

CSE 143 Lecture 25. I/O Streams; Exceptions; Inheritance. read 9.3, 6.4. slides adapted from Marty Stepp

Inheritance. Notes Chapter 6 and AJ Chapters 7 and 8

Transcription:

Writing classes Inheritance Readings: 9.1 Write an Employee class with methods that return values for the following properties of employees at a particular company: Work week: 40 hours Annual salary: $40,000 Paid time off: 2 weeks Leave of absence form: Yellow form 1 2 Employee class Writing more classes // A class to represent employees public class Employee { // works 40 hours / week return 40000.0; // $40,000.00 / year // 2 weeks' paid vacation return "yellow"; // use the yellow form 3 Write a Secretary class with methods that return values for the following properties of secretaries at a particular company: Work week: 40 hours Annual salary: $40,000 Paid time off: 2 weeks Leave of absence form: Yellow form Add a method takedictation that takes a string as a parameter and prints out the string prefixed by "Taking dictation of text: ". 4 Secretary class Why are they very similar? public class Secretary { // works 40 hours / week return 40000.0; // $40,000.00 / year // 2 weeks' paid vacation return "yellow"; // use the yellow form // A class to represent employees public class Employee { return 40000.0; return "yellow"; public class Secretary { return 40000.0; return "yellow"; System.out.println("Taking dictation of text: " + text); System.out.println("Taking dictation of text: " + text); 5 6 1

Is-a relationship Reusing code: why re-invent the wheel? is-a relationship: A hierarchical connection where one category can be treated as a specialized version of another. Examples: Every secretary is an employee. Every dog is a mammal. Every refrigerator is an appliance. code reuse: The practice of writing program code once and using it in many contexts. We'd like to be able to say the following: public class Secretary { <copy all the contents from Employee class> System.out.println("Taking dictation of text: " + text); 7 8 Inheritance Inheritance syntax inheritance: A way to specify a relationship between two classes where one class inherits the state and behavior of another. The child class (also called subclass) inherits from the parent class (also called superclass). The subclass receives a copy of every field and method from the superclass. Creating a subclass, general syntax: public class <subclass name> extends <superclass name> { Example: public class Secretary extends Employee {... By extending Employee, each Secretary object receives a gethours, getsalary, getvacationdays, and getvacationform method automatically. 9 10 Improved Secretary class Writing even more classes public class Secretary extends Employee { System.out.println("Taking dictation of text: " + text); Write a Marketer class that represents marketers who have the same properties as general employees, but instead of making only a paltry $40,000, marketers make $50,000! Can we still leverage the Employee class or do we have to re-write everything, because one method (getsalary) is different? If only Marketer could write a new version of the getsalary method, but inherit everything else 11 12 2

Overriding methods Marketer class override: To write a new version of a method in a subclass to replace the superclass's version. To override a superclass method, just write a new version of it in the subclass. This will replace the inherited version. // A class to represent marketers public class Marketer extends Employee { public void advertise() { System.out.println("Act now while supplies last!"); return 50000.0; // $50,000.00 / year 13 14 Based in reality or too convenient? Rules, rules, everywhere At many companies, all new employees attend a common orientation to learn general rules (e.g., what forms to fill out when). Each person receives a big manual of these rules. The smaller manual adds some rules and also changes (read: overrides) some rules from the large manual (e.g., "use the pink form instead of the yellow form") Each employee also attends a subdivision-specific orientation to learn rules specific to their subdivision (e.g., marketing department). Everyone receives a smaller manual of these rules. 15 16 Why bother with separate manuals? Advantages of separate manuals maintenance: If a common rule changes, only the common manual needs to be updated. locality: A person can look at the manual for lawyers and quickly discover all rules that are specific to lawyers. Why not just have a 22-page manual for lawyers, 21-page manual for secretaries, 23-page manual for marketers, etc? 17 18 3

Key ideas Exercise: LegalSecretary It is useful to be able to specify general rules that will apply to many groups (the 20-page manual). It is also useful to specify a smaller set of rules for a particular group, including being able to replace rules from the overall set (e.g., "use the pink form instead of the yellow form"). Write a LegalSecretary class that represents legal secretaries a special type of secretary that can file legal briefs. Legal secretaries also earn more money ($45,000). 19 20 Solution: LegalSecretary Inheritance hierarchies // A class to represent legal secretaries public class LegalSecretary extends Secretary { public void filelegalbriefs() { System.out.println("I could file all day!"); return 45000.0; // $45,000.00 / year Deep hierarchies can be created by multiple levels of subclassing. inheritance hierarchy: A set of classes connected by is-a relationships that can share common code. 21 22 Exercise: Lawyer Solution: Lawyer Lawyers are employees that know how to sue. They get an extra week of paid vacation (a total of 3) and have to use the pink form when applying for vacation leave. Write the Lawyer class. // A class to represent lawyers public class Lawyer extends Employee { // overrides getvacationform from Employee class return "pink"; // overrides getvacationdays from Employee class public int getvacation() { return 15; // 3 weeks vacation public void sue() { System.out.println("I'll see you in court!"); 23 24 4

Motivation Polymorphism Readings: 9.2 Given the following: Lawyer laura = new Lawyer(); Marketer mark = new Marketer(); Write a program that will print out the salaries and the color of the vacation form for each employee. 25 26 Polymorphism Properties of polymorphism A reference variable of type T can refer to an object of any subclass of T. Employee person = new Lawyer(); polymorphism: The ability for the same code to be used with several different types of objects and behave differently depending on the type of object used. Employee person = new Lawyer(); System.out.println(person.getSalary()); // 40000.0 System.out.println(person.getVacationForm()); // "pink" You can call any method from Employee on the person variable, but not any method specific to Lawyer (such as sue). Once a method is called on the object, it behaves in its normal way (as a Lawyer, not as a normal Employee). 27 28 Polymorphism and parameters Polymorphism and arrays public class EmployeeMain { public static void main(string[] args) { Lawyer laura = new Lawyer(); Marketer mark = new Marketer(); printinfo(laura); printinfo(mark); public static void printinfo(employee empl) { System.out.println("salary = " + empl.getsalary()); System.out.println("days = " + empl.getvacationdays()); System.out.println("form = " + empl.getvacationform()); Output: salary = 40000.0 vacation days = 15 vacation form = pink salary = 50000.0 vacation form = yellow 29 public class EmployeeMain2 { public static void main(string[] args) { Employee[] employees = { new Lawyer(), new Secretary(), new Marketer(), new LegalSecretary() ; for (int i = 0; i < employees.length; i++) { System.out.println("salary = " + employees[i].getsalary()); System.out.println("vacation days = " + employees[i].getvacationdays()); Output: salary = 40000.0 vacation days = 15 salary = 40000.0 salary = 50000.0 salary = 45000.0 30 5

Exercise 1 Exercise 1 Assume that the following four classes have been declared: What would be the output of the following client code? public class Foo { public void method1() { System.out.println(""); public void method2() { System.out.println(" 2"); return ""; public class Bar extends Foo { public void method2() { System.out.println("bar 2"); public class Baz extends Foo { public void method1() { System.out.println(""); return ""; public class Mumble extends Baz { public void method2() { System.out.println("mumble 2"); Foo[] pity = { new Baz(), new Bar(), new Mumble(), new Foo() ; for (int i = 0; i < pity.length; i++) { System.out.println(pity[i]); pity[i].method1(); pity[i].method2(); 31 32 Diagramming polymorphic code Finding output with tables method Foo Bar Baz Mumble method1 method2 2 bar 2 2 mumble 2 tostring 33 34 Solution 1 Exercise 2 The code produces the following output: 2 bar 2 mumble 2 2 Assume that the following four classes have been declared: public class Lamb extends { public void b() { System.out.println(""); public class { public void a() { System.out.println(" a"); public void b() { System.out.println(" b"); return ""; public class Spam extends { public void a() { System.out.println("Spam a"); public class extends Lamb { public void a() { System.out.println(" a"); return ""; 35 36 6

Exercise 2 Diagramming polymorphic code What would be the output of the following client code? [] d = { new Spam(), new (), new (), new Lamb() ; for (int i = 0; i < d.length; i++) { System.out.println(d[i]); d[i].a(); d[i].b(); 37 38 Finding output with tables Solution 2 The code produces the following output: method Lamb Spam Spam a a b tostring a b a a Spam a a a b a 39 40 7