Topic 31 - inheritance

Similar documents
Building Java Programs

AP Computer Science. Interactions with superclass

Lecture 15: Inheritance II

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

AP Computer Science. Gridworld, inheritance

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

CS 112 Introduction to Programming

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

ADTs, Interfaces, Inheritance & Polymorphism

CS 112 Introduction to Programming

Admin. q Admin and recap q Class inheritance

CS 112 Introduction to Programming. (Spring 2012)

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

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

Programming Abstractions

Programming Abstractions

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

Building Java Programs. Inheritance and Polymorphism

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

Arrays Classes & Methods, Inheritance

OVERRIDING. 7/11/2015 Budditha Hettige 82

Super-Classes and sub-classes

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

Polymorphism 2/12/2018. Which statement is correct about overriding private methods in the super class?

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

CSE 143 Lecture 12 Inheritance

INHERITANCE & POLYMORPHISM. INTRODUCTION IB DP Computer science Standard Level ICS3U. INTRODUCTION IB DP Computer science Standard Level ICS3U

ECE 122. Engineering Problem Solving with Java

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

Comp 249 Programming Methodology

Basic Object-Oriented Concepts. 5-Oct-17

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

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

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

CSE 143 Lecture 21. I/O Streams; Exceptions; Inheritance. read 9.3, 6.4. slides created by Marty Stepp

CSE 143 Lecture 22. I/O Streams; Exceptions; Inheritance. read 9.3, 6.4. slides created by Marty Stepp

Inheritance -- Introduction

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

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

INHERITANCE. Spring 2019

Chapter 7. Inheritance

Chapter 14 Abstract Classes and Interfaces

CS313D: ADVANCED PROGRAMMING LANGUAGE

Inheritance and Encapsulation. Amit Gupta

Inheritance. Transitivity

CSE 303 Lecture 23. Inheritance in C++ slides created by Marty Stepp

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

Java Object Oriented Design. CSC207 Fall 2014

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

CREATED BY: Muhammad Bilal Arslan Ahmad Shaad. JAVA Chapter No 5. Instructor: Muhammad Naveed

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

CIS 110: Introduction to computer programming

Overview of OOP. Dr. Zhang COSC 1436 Summer, /18/2017

BBM 102 Introduction to Programming II

Overriding Variables: Shadowing

Object Orientated Programming Details COMP360

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

CS111: PROGRAMMING LANGUAGE II

ASSIGNMENT NO 13. Objectives: To learn and understand concept of Inheritance in Java

CISC 3115 TY3. C09a: Inheritance. Hui Chen Department of Computer & Information Science CUNY Brooklyn College. 9/20/2018 CUNY Brooklyn College

Practice for Chapter 11

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

ENCAPSULATION AND POLYMORPHISM

Inheritance & Polymorphism

Inheritance. Benefits of Java s Inheritance. 1. Reusability of code 2. Code Sharing 3. Consistency in using an interface. Classes

Java Inheritance. Written by John Bell for CS 342, Spring Based on chapter 6 of Learning Java by Niemeyer & Leuck, and other sources.

One of these "compartments" is more correctly referred to as an element of the array

Programming Language Concepts: Lecture 2

BBM 102 Introduction to Programming II Spring Inheritance

CS-202 Introduction to Object Oriented Programming

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

Programming Language Concepts Object-Oriented Programming. Janyl Jumadinova 28 February, 2017

Inheritance and Polymorphism. CS180 Fall 2007

Course Content. Objectives of Lecture 24 Inheritance. Outline of Lecture 24. Inheritance Hierarchy. The Idea Behind Inheritance

Course Content. Objectives of Lecture 24 Inheritance. Outline of Lecture 24. CMPUT 102: Inheritance Dr. Osmar R. Zaïane. University of Alberta 4

BBM 102 Introduction to Programming II Spring 2017

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

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

Data Structures (list, dictionary, tuples, sets, strings)

CS313D: ADVANCED PROGRAMMING LANGUAGE

Rules and syntax for inheritance. The boring stuff

Inheritance and Polymorphism

C++ Important Questions with Answers

Lecture 18 CSE11 Fall 2013 Inheritance

Pieter van den Hombergh Thijs Dorssers Stefan Sobek. February 10, 2017

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

Software and Programming 1

9/10/2018 Programming Data Structures Inheritance

WEEK 13 EXAMPLES: POLYMORPHISM

Inheritance and Polymorphism

Classes and Inheritance Extending Classes, Chapter 5.2

Inheritance and Interfaces

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

Chapter 11 Inheritance and Polymorphism. Motivations. Suppose you will define classes to model circles,

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

CS11 Introduction to C++ Fall Lecture 7

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

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

Inheritance. COMP Week 12

Transcription:

Topic 31 - inheritance Hierarchies Hierarchies used to organize organizations and information Kingdom - Animalia More general Phylum - Chordata Class- Mammalia Order - Carnivora Family - Felidae Genus - Felinae Species - F. catus More specific 2 1

Hierarchies Object oriented languages provide a mechanism to create hierarchies among data types in a program and in code libraries Used for organization, modeling the problem, and to avoid redundant code When a new data type is a specialization or variation on an existing data type use inheritance to capture the relationship and avoid redundancy of code 3 Inheritance in Practice 1. extends keyword 2. inheritance of instance methods 3. inheritance of instance variables 4. object initialization and constructors 5. calling a parent constructor with super() 6. overriding methods 7. partial overriding, super.parentmethod() 8. inheritance requirement in Java 9. the Object class 10. inheritance hierarchies 4 2

Pretty Stone Implement a Pretty Stone class Same as a Stone except alternates Color every (N + 1) times based on an int parameter to the constructor If parameter is [0..2] alternates between BLUE and RED If parameter [3..5] alternates between GREEN and YELLOW If parameter > 5 alternates between MAGENTA and ORANGE Pretty stones always return true when asked to eat. 5 Rolling Stone Implement a Rolling Stone class Same as a Pretty Stone... except when a Rolling Stone is created it picks a random number of turns based on the int sent to the constructor. 0 -> 0-99, 1 -> 100-199, 2 -> 200-299 Stays still until asked to move that number of times, then moves North fights: if not moving yet same as pretty stone, otherwise a random attack 6 3

Another Example Following slides contain another example of an inheritance hierarchy and Java syntax for implementing it. 7 Law firm employee analogy common rules: hours, vacation, benefits, regulations... all employees attend a common orientation to learn general company rules each employee receives a 20-page manual of common rules each subdivision also has specific rules: employee receives a smaller (1-3 page) manual of these rules smaller manual adds some new rules and also changes some rules from the large manual 8 4

Employee regulations Consider the following employee regulations: Employees work 40 hours / week. Employees make $40,000 per year, except legal secretaries who make $5,000 extra per year ($45,000 total), and marketers who make $10,000 extra per year ($50,000 total). Employees have 2 weeks of paid vacation leave per year, except lawyers who get an extra week (a total of 3). Employees should use a yellow form to apply for leave, except for lawyers who use a pink form. Each type of employee has some unique behavior: Lawyers know how to sue. Marketers know how to advertise. Secretaries know how to take dictation. Legal secretaries know how to prepare legal documents. 9 An Employee class // A class to represent employees in general (20-page manual). public class Employee { public int gethours() { return 40; // works 40 hours / week return 40000.0; // $40,000.00 / year public int getvacationdays() { return 10; // 2 weeks' paid vacation public String getvacationform() { return "yellow"; // use the yellow form Exercise: Implement class Secretary, based on the previous employee regulations. (Secretaries can take dictation.) 10 5

Redundant Secretary class // A redundant class to represent secretaries. public class Secretary { public int gethours() { return 40; // works 40 hours / week return 40000.0; // $40,000.00 / year public int getvacationdays() { return 10; // 2 weeks' paid vacation public String getvacationform() { return "yellow"; // use the yellow form public void takedictation(string text) { System.out.println("Taking dictation of text: " + text); 11 Desire for code-sharing takedictation 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 takedictation(string text) { System.out.println("Taking dictation of text: " + text); 12 6

Inheritance inheritance: A way to form new classes based on existing classes, taking on their attributes/behavior. a way to group related classes a way to share code between two or more classes One class can extend another, absorbing its data/behavior. superclass: The parent class that is being extended. subclass: The child class that extends the superclass and inherits its behavior. Subclass gets a copy of every field and method from superclass 13 Inheritance syntax public class <name> extends <superclass> { Example: public class Secretary extends Employee {... By extending Employee, each Secretary object now: receives a gethours, getsalary, getvacationdays, and getvacationform method automatically can be treated as an Employee by client code (seen later) 14 7

Improved Secretary code // A class to represent secretaries. public class Secretary extends Employee { public void takedictation(string text) { System.out.println("Taking dictation of text: " + text); Now we only write the parts unique to each type. Secretary inherits gethours, getsalary, getvacationdays, and getvacationform methods from Employee. Secretary adds the takedictation method. 15 Implementing Lawyer Consider the following lawyer regulations: Lawyers who get an extra week of paid vacation (a total of 3). Lawyers use a pink form when applying for vacation leave. Lawyers have some unique behavior: they know how to sue. Problem: We want lawyers to inherit most behavior from employee, but we want to replace parts with new behavior. 16 8

Lawyer class // A class to represent lawyers. public class Lawyer extends Employee { // overrides getvacationform from Employee class public String getvacationform() { return "pink"; // overrides getvacationdays from Employee class public int getvacationdays() { return 15; // 3 weeks vacation public void sue() { System.out.println("I'll see you in court!"); Exercise: Complete the Marketer class. Marketers make $10,000 extra ($50,000 total) and know how to advertise. 17 Marketer class // 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 18 9

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 ($5,000 more) and can file legal briefs. public class LegalSecretary extends Secretary {... Exercise: Complete the LegalSecretary class. 19 LegalSecretary class // 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 20 10

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 $50,000. Legal secretaries now make $55,000. Marketers now make $60,000. We must modify our code to reflect this policy change. 21 Modifying the superclass // A class to represent employees in general (20-page manual). public class Employee { public int gethours() { return 40; // works 40 hours / week return 50000.0; // $50,000.00 / year... Are we finished? The Employee subclasses are still incorrect. They have overridden getsalary to return other values. 22 11

An unsatisfactory solution public class LegalSecretary extends Secretary { return 55000.0;... public class Marketer extends Employee { return 60000.0;... Problem: The subclasses' salaries are based on the Employee salary, but the getsalary code does not reflect this. 23 Calling overridden methods Subclasses can call overridden methods with super super.<method>(<parameters>) Example: public class LegalSecretary extends Secretary { double basesalary = super.getsalary(); return basesalary + 5000.0;... Exercise: Modify Lawyer and Marketer to use super. 24 12

Improved subclasses public class Lawyer extends Employee { public String getvacationform() { return "pink"; public int getvacationdays() { return super.getvacationdays() + 5; public void sue() { System.out.println("I'll see you in court!"); public class Marketer extends Employee { public void advertise() { System.out.println("Act now while supplies last!"); return super.getsalary() + 10000.0; 25 Given the Employee class to the right what is output by the following code? Employee e1; e1 = new Employee("#1"); String str; str = e1.tostring(); System.out.println(str); A. #1 B. "#1" C. Output varies each time. D. Syntax error E. Runtime error // A class to represent employees public class Employee { private String id; public Employee(String id) { this.id = id; public int gethours() { return 40; return 40000.0; public int getvacationdays() { return 10; public String getvacationform() { return "yellow"; 26 13