CSE 143 Lecture 12 Inheritance

Similar documents
CSE 143 Lecture 22. The Object class; Polymorphism. read slides created by Marty Stepp and Ethan Apter

Building Java Programs. Inheritance and Polymorphism

AP Computer Science. Gridworld, inheritance

Section: Inheritance Heck

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

Inheritance, Polymorphism, and Interfaces

CS111: PROGRAMMING LANGUAGE II

Lecture 18 CSE11 Fall 2013 Inheritance

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

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

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

CS313D: ADVANCED PROGRAMMING LANGUAGE

CS313D: ADVANCED PROGRAMMING LANGUAGE

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

Lecture 15: Inheritance II

1B1b Inheritance. Inheritance. Agenda. Subclass and Superclass. Superclass. Generalisation & Specialisation. Shapes and Squares. 1B1b Lecture Slides

Java Object Oriented Design. CSC207 Fall 2014

More On inheritance. What you can do in subclass regarding methods:

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

Inheritance and Polymorphism

CSc 335 Inheritance Hell

Building Java Programs

Object Oriented Programming: Based on slides from Skrien Chapter 2

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

COMP 110/L Lecture 19. Kyle Dewey

Pointers, Arrays and Parameters

Inheritance. Lecture 11 COP 3252 Summer May 25, 2017

09/02/2013 TYPE CHECKING AND CASTING. Lecture 5 CS2110 Spring 2013

AP Computer Science. Interactions with superclass

COMP 250 Fall inheritance Nov. 17, 2017

CS/ENGRD 2110 SPRING 2018

INHERITANCE. Spring 2019

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

Super-Classes and sub-classes

Everything is an object. Almost, but all objects are of type Object!

Topic 31 - inheritance

CS112 Lecture: Extending Classes and Defining Methods

Polymorphism and Inheritance

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

CS 61B Discussion 4: Inheritance Fall 2018

CS/ENGRD 2110 FALL Lecture 6: Consequence of type, casting; function equals

Intro to Computer Science 2. Inheritance

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

16 Multiple Inheritance and Extending ADTs

Inheritance -- Introduction

Basic Object-Oriented Concepts. 5-Oct-17

CS 112 Introduction to Programming. (Spring 2012)

Introduction to Object-Oriented Programming

Programming Abstractions

INSTRUCTIONS TO CANDIDATES

Programming in the large

Need to store a list of shapes, each of which could be a circle, rectangle, or triangle

For this chapter, switch languages in DrRacket to Advanced Student Language.

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

CSSE 220 Day 15. Inheritance. Check out DiscountSubclasses from SVN

Unit3: Java in the large. Prepared by: Dr. Abdallah Mohamed, AOU-KW

1: Introduction to Object (1)

Chapter 5 Object-Oriented Programming

Rules and syntax for inheritance. The boring stuff

VIRTUAL FUNCTIONS Chapter 10

More Relationships Between Classes

Week 7. Statically-typed OO languages: C++ Closer look at subtyping

CS/ENGRD 2110 FALL Lecture 6: Consequence of type, casting; function equals

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

1.00 Lecture 14. Exercise: Plants

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

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

Inheritance, polymorphism, interfaces

CSC9T4: Object Modelling, principles of OO design and implementation

Object-Oriented Design Lecture 14 CSU 370 Fall 2007 (Pucella) Friday, Nov 2, 2007

CSE 143 SAMPLE MIDTERM

Java Programming Lecture 7

Implements vs. Extends When Defining a Class

Inheritance. Exploring Polymorphism. Mairead Meagher Dr. Siobhán Drohan. Produced by: Department of Computing and Mathematics

CSIS 10B Lab 2 Bags and Stacks

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

More on Objects in JAVA TM

CS-202 Introduction to Object Oriented Programming

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

CS111: PROGRAMMING LANGUAGE II

CS 112 Introduction to Programming

AP CS Unit 6: Inheritance Notes

type conversion polymorphism (intro only) Class class

Programming Abstractions

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

Main Topics. Study Tactics. Exam Structure, Roughly. Java Fundamentals. CISC 3120 Midterm Review Guide

CS 251 Intermediate Programming Inheritance

Object-Oriented Programming

CS/ENGRD 2110 SPRING Lecture 7: Interfaces and Abstract Classes

Java Review: Objects

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

Introduction to Object-Oriented Programming

CSE 331 Final Exam 12/9/13

CS111: PROGRAMMING LANGUAGE II

Survey #2. Programming Assignment 3. Final Exam. University of British Columbia CPSC 111, Intro to Computation Alan J. Hu.

Polymorphism. Object Orientated Programming in Java. Benjamin Kenwright

Introduction to Computation and Problem Solving

Lecture 11. Demonstration #1. More Inheritance, More Constructors. Absolute C++ Chapter 15. Virtual Functions. Overriding

CSE 331 Final Exam 3/16/15 Sample Solution

1.00 Lecture 13. Inheritance

Transcription:

CSE 143 Lecture 12 Inheritance slides created by Ethan Apter http://www.cs.washington.edu/143/

Intuition: Employee Types Consider this (partial) hierarchy of employee types: Employee Clerical Professional Secretary Lawyer Engineer Legal Secretary What kind of tasks can each employee type perform? 2

Intuition: Employee Types What tasks should all employees be able to do? show up for work work collect paychecks What tasks can a lawyer do that an engineer cannot? sue file legal briefs Which kind of secretary (regular or legal) can accomplish a greater variety of tasks? legal secretaries can do all regular secretarial work and have special training for additional tasks 3

Intuition: Employee Training On your first day at work, you ll likely receive some general training for your new job If it s a big company (like Microsoft), you ll likely receive this with many other types of employees engineers, business people, lawyers, etc After this general training, you ll probably receive some specialized training I know yesterday they told you to fill out your time-card on the white sheet, but here we do it online instead We call this kind of replacement overriding the new behavior overrides/replaces the old behavior 4

Inheritance Overview Java does something similar with inheritance If we want to show an inheritance relationship between two classes, we use the extends keyword: public class B extends A {... Which sets up the following inheritance hierarchy: A superclass B subclass 5

Superclasses and Subclasses In the previous example, A is the superclass of B (A is above B on the hierarchy), and B is a subclass of A (B is below A on the hierarchy) This wording is somewhat different from standard English: hamburger bacon cheeseburger superclass subclass So, a super bacon cheeseburger is just a hamburger that doesn t seem right: it s missing bacon and cheese! but that s how inheritance works 6

Base and Derived Classes We also say A is the base class of B, and B is a derived class of A This makes a little more sense: hamburger bacon cheeseburger base class derived class A hamburger provides the basic form of a bacon cheeseburger. Alternately, a bacon cheeseburger is a hamburger with minor additions 7

Extending Object Consider the class A that we ve been discussing: public class A {... We didn t write that A extends anything, but it automatically extends Object: Object A B This diagram is more complete than before. However, we often don t draw Object because we know it must be there All the classes you ve written so far extend Object 8

Object Object is a very general class Since every class must extend Object, either directly like A or indirectly like B, Object must have only state and behavior that is needed by every class: equals tostring this is where the weird default tostring comes from and more (but we won t bother with the others) Why doesn t Object contain a compareto method? 9

Why Use Inheritance? Inheritance allows us to reuse code we ve already written this makes it a powerful tool Inheritance also allows us to express the core relationship between different classes Subclasses allow us to do two things: add new state and behavior (fields and methods) useful when a superclass has most of the needed state and behavior override inherited methods useful when you need to modify the way an inherited method functions 10

Substituting When can we substitute one object for another? Recall our employee hierarchy: Employee most simple and generic Clerical Professional Secretary Lawyer Engineer Legal Secretary most complex and specific 11

Substituting We can always substitute a more specific object for a less specific one. With inheritance, we call this an is-a relationship a lawyer is-a professional employee is-an employee a lawyer can substitute for an employee, etc a legal secretary is-a secretary is-a clerical employee is-an employee a legal secretary can substitute for a secretary, etc You can see the is-a relationship by moving up the inheritance hierarchy It s not ok to substitute across the hierarchy a secretary is NOT a lawyer and can t substitute for one 12

Substituting Recall our classes B and A (B extends A) Obviously we can do this: A x = new A(); B y = new B(); variable type object type But what if the variable type and object type don t match? A x = new B(); B y = new A(); perfectly fine not good! 13

Substituting But, what does it mean when the variable type doesn t match the object type? A x = new B(); We are limited to the behaviors of the variable type for x above, we are limited to using only methods defined for class A (which may be inherited from Object) When executed, the methods will behave as defined in the object type for x above, the methods will execute as defined in B (which may be inherited from A or Object) 14

Casting Suppose that: you re an unemployed legal secretary you know that legal secretaries earn $20 an hour you know that generic secretaries earn $15 an hour you accept a job as a generic secretary for $15 an hour So far, this is fine (just not ideal) But what if: your employer discovers that you re a legal secretary...and wants you to do legal secretary work...for just $15 an hour? Is that ok? 15

Casting No, it s not ok! If he wants you to do legal secretary work, he can renegotiate your contract to reflect this and pay you $20 an hour Java lets us do something similar when we class cast the class cast essentially renegotiates the contract Secretary you = new LegalSecretary(); LegalSecretary youwithraise = (LegalSecretary)you; cast 16

Exercise: Inheritance Mystery 4-5 classes with inheritance relationships are shown the class names won t make sense (inheritance mystery) A client program calls methods on objects of each class some questions involve casting some lines of code are illegal and produce errors You must read the code and determine what it does if it produces output, you must be precise if it produces an error, you need to specify what kind of error (either a compiler error or a runtime error) A similar problem will be on your midterm! 17

Exercise: Inheritance Mystery Assume that the following classes have been declared: public class Fog extends Sleet { public void method1() { System.out.println("Fog 1"); public void method3() { System.out.println("Fog 3"); public class Rain extends Snow { public void method1() { System.out.println("Rain 1"); public void method2() { System.out.println("Rain 2"); 18

Exercise: Inheritance Mystery public class Sleet extends Snow { public void method2() { System.out.println("Sleet 2"); super.method2(); method3(); public void method3() { System.out.println("Sleet 3"); public class Snow { public void method2() { System.out.println("Snow 2"); public void method3() { System.out.println("Snow 3"); 19

Technique: Diagramming First, determine the inheritance hierarchy: Object Snow Rain Sleet Fog 20

Technique: Diagramming...and determine where methods are defined and inherited Object Snow method2 method3 Rain method1 method2 (method3) Sleet method2 method3 Fog method1 (method2) method3 21

Method Calls Let s look a little closer at Sleet s method2(): public class Sleet extends Snow { public void method2() { System.out.println("Sleet 2"); super.method2(); method3();... super is a Java keyword to look to the super class so super.method2() is like saying Snow.method2() super is static: it always refers to Snow s methods however, the call on method3 is dynamic it always runs the current version of method3, because it s possible that another subclass can redefine method3 22

Technique: Behavior Table Then, figure out the behaviors of each type of object method Snow Rain Sleet Fog method1 --- Rain 1 --- Fog 1 method2 Snow 2 Rain 2 Sleet 2 Snow 2 method3() Sleet 2 Snow 2 method3() method3 Snow 3 Snow 3 Sleet 3 Fog 3 Italics - inherited behavior Circled - dynamic method call 23

Exercise What happens when the following examples are executed? Example 1 (letter a on handout #15): Snow var1 = new Sleet(); var1.method3(); Example 2 (letter c on handout #15): Snow var1 = new Sleet(); var1.method2(); Example 3 (letter o on handout #15): Snow var3 = new Fog(); ((Sleet)var3).method1(); Example 4 (letter m on handout #15): Snow var3 = new Fog(); ((Rain)var3).method1(); 24

Example 1 Problem: Snow var1 = new Sleet(); var1.method3(); Output: Sleet 3 Rain method1 method2 (method3) variable Snow method2 method3 object Sleet method2 method3 Fog method1 (method2) method3 25

Example 2 Problem: Snow var1 = new Sleet(); var1.method2(); Output: Sleet 2 Snow 2 Sleet 3 Rain method1 method2 (method3) variable Snow method2 method3 object Sleet method2 method3 Fog method1 (method2) method3 26

Example 3 Problem: Snow var3 = new Fog(); ((Sleet)var3).method1(); Output: No output! Compiler error! Sleet doesn t have a method1()! Rain method1 method2 (method3) Snow method2 method3 Sleet method2 method3 variable object Fog method1 (method2) method3 27

Example 4 Problem: Snow var3 = new Fog(); ((Rain)var3).method1(); Output: No output! Runtime error! A Fog is not a Rain! variable Rain method1 method2 (method3) Snow method2 method3 Sleet method2 method3 object Fog method1 (method2) method3 28

Solving Inheritance Mystery Steps to solving inheritance mystery: 1. Look at the variable type (if there is a cast, look at the casted variable type). If the variable type does not have the requested method the compiler will report an error. 2. If there was a cast, make sure the casted variable type is compatible with the object type (i.e. ensure the object type is a subclass of the variable type). If they are not compatible, a runtime error (ClassCastException) will occur. 3. Execute the method in question, behaving like the object type (the variable type and casted variable type no longer matter at all) 29

Solutions to Handout #15 Solutions for letters a through j: Letter Code Output a var1.method1(); compiler error b var2.method1(); Rain 1 c var1.method2(); Sleet 2/Snow 2/Sleet 3 d var2.method2(); Rain 2 e var3.method2(); Sleet 2/Snow 2/Fog 3 f var4.method2(); compiler error g var5.method2(); Sleet 2/Snow 2/Fog 3 h var1.method3(); Sleet 3 i var2.method3(); Snow 3 j var3.method3(); Fog 3 30

Solutions to Handout #15 Solutions for letters k through t: Letter Code Output k var4.method3(); compiler error l var5.method3(); Fog 3 m ((Rain)var3).method1(); runtime error n ((Fog)var5).method1(); Fog 1 o ((Sleet)var3).method1(); compiler error p ((Sleet)var3).method3(); Fog 3 q ((Fog)var6).method3(); runtime error r ((Snow)var4).method2(); Snow 2 s ((Sleet)var4).method3(); runtime error t ((Rain)var6).method3(); Snow 3 31