CSE 143 Lecture 12 Inheritance slides created by Ethan Apter

Slides:



Advertisements
Similar presentations
OO Programming in Java Objectives for today: Overriding the toString() method Polymorphism & Dynamic Binding Interfaces Packages and Class Path.
Advertisements

1 l Inheritance Basics l Programming with Inheritance l Dynamic Binding and Polymorphism Inheritance.
Georgia Institute of Technology Workshop for CS-AP Teachers Chapter 3 Advanced Object-Oriented Concepts.
Java™ How to Program, 9/e Presented by: Dr. José M. Reyes Álamo © Copyright by Pearson Education, Inc. All Rights Reserved.
ACM/JETT Workshop - August 4-5, :Inheritance and Interfaces.
Inheritance. Extending Classes It’s possible to create a class by using another as a starting point  i.e. Start with the original class then add methods,
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Copyright 2006 by Pearson Education 1 Building Java Programs Chapter 9: Inheritance and Interfaces.
1 Evan Korth New York University abstract classes and casting Professor Evan Korth New York University.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 13 Polymorphism is-a relationships Interfaces.
(c) University of Washington03-1 CSC 143 Java Inheritance Reading: Ch. 10.
Copyright 2008 by Pearson Education Building Java Programs Chapter 9 Lecture 9-1: Inheritance reading:
1 Java Inheritance. 2 Inheritance On the surface, inheritance is a code re-use issue. –we can extend code that is already written in a manageable manner.
CMSC 202 Generics. Nov Generalized Code One goal of OOP is to provide the ability to write reusable, generalized code. Polymorphic code using.
Inheritance and Polymorphism Daniel Liang, Introduction to Java Programming.
CSC 142 Computer Science II Zhen Jiang West Chester University
Copyright 2008 by Pearson Education Building Java Programs Chapter 9 Lecture 9-1: Inheritance reading:
CSE 143 Lecture 23 Polymorphism; the Object class read slides created by Marty Stepp and Ethan Apter
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
Some Object-Oriented Programming (OOP) Review. Let’s practice writing some classes Write an Employee class with methods that return values for the following.
1 final (the keyword, not the exam). 2 Motivation Suppose we’ve defined an Employee class, and we don’t want someone to come along and muck it up  E.g.,
Object Oriented Software Development
 All calls to method toString and earnings are resolved at execution time, based on the type of the object to which currentEmployee refers.  Known as.
1 Building Java Programs Chapter 9: Inheritance and Interfaces These lecture notes are copyright (C) Marty Stepp and Stuart Reges, They may not be.
Copyright 2008 by Pearson Education Building Java Programs Chapter 9 Lecture 9-2: Static Data; More Inheritance reading:
M1G Introduction to Programming 2 5. Completing the program.
Inheritance CSI 1101 Nour El Kadri. OOP  We have seen that object-oriented programming (OOP) helps organizing and maintaining large software systems.
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Copyright 2010 by Pearson Education Building Java Programs Chapter 9 Lecture 9-1: Inheritance reading: 9.1.
Copyright 2008 by Pearson Education Building Java Programs Chapter 9 Lecture 9-2: Interacting with the Superclass ( super ) reading:
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Inheritance and Class Hierarchies Chapter 3. Chapter Objectives  To understand inheritance and how it facilitates code reuse  To understand how Java.
Inheritance and Polymorphism. Superclass and Subclass Inheritance defines a relationship between objects that share characteristics. It is a mechanism.
CMSC 202 Polymorphism. 10/20102 Topics Binding (early and late) Upcasting and downcasting Extensibility The final modifier with  methods  classes.
Inheritance ndex.html ndex.htmland “Java.
Inheritance and Polymorphism
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Object-Oriented Programming: Polymorphism Chapter 10.
Copyright 2008 by Pearson Education Building Java Programs Chapter 9: Inheritance and Interfaces Lecture 9-1.
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2015 Lecture 20 – C++ Subclasses and Inheritance.
CSCI-383 Object-Oriented Programming & Design Lecture 17.
Lecture 5:Interfaces and Abstract Classes Michael Hsu CSULA.
Lecture 6:Interfaces and Abstract Classes Michael Hsu CSULA.
CSE 143 Lecture 13 Inheritance slides created by Ethan Apter
1 Interacting with the superclass (continued) suggested reading:9.4.
Lecture 16: Polymorphism (Part I)
Lecture 5:Interfaces and Abstract Classes
Lecture 25: Inheritance and Polymorphism
Inheritance Based on slides by Ethan Apter
Building Java Programs Chapter 9
Adapted from slides by Marty Stepp and Stuart Reges
Inheritance and Polymorphism
Lecture 15: More Inheritance
Lecture 9-2: Interacting with the Superclass (super);
CSE 143 Lecture 22 The Object class; Polymorphism read
Adapted from slides by Marty Stepp and Stuart Reges
Chapter 9 Object-Oriented Programming: Inheritance
CSE 143 Lecture 22 The Object class; Polymorphism read
CSE 143 Lecture 24 Inheritance and the Object class; Polymorphism
Inheritance Readings: 9.1.
Lecture 17: Polymorphism (Part I)
Lecture 15: Inheritance II
Polymorphism 2019/4/29.
Building Java Programs
CSE 143 Lecture 23 Polymorphism; the Object class read
CSE 143 Lecture 24 Inheritance and the Object class; Polymorphism
CSE 143 Lecture 24 Inheritance and the Object class; Polymorphism
CSE 143 Lecture 23 Inheritance and the Object class; Polymorphism
Presentation transcript:

CSE 143 Lecture 12 Inheritance slides created by Ethan Apter

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

3 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

4 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

5 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 B superclass subclass

6 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: 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 hamburger bacon cheeseburger superclass subclass

7 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: A hamburger provides the basic form of a bacon cheeseburger. Alternately, a bacon cheeseburger is a hamburger with minor additions hamburger bacon cheeseburger base class derived class

8 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 : All the classes you’ve written so far extend Object A B Object This diagram is more complete than before. However, we often don’t draw Object because we know it must be there

9 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?

10 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

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

12 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

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

14 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 )

15 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?

16 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

17 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!

18 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"); }

19 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"); }

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

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

22 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

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

24 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();

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

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

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

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

29 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)

30 Solutions to Handout #15 Solutions for letters a through j: LetterCodeOutput avar1.method1();compiler error bvar2.method1();Rain 1 cvar1.method2();Sleet 2/Snow 2/Sleet 3 dvar2.method2();Rain 2 evar3.method2();Sleet 2/Snow 2/Fog 3 fvar4.method2();compiler error gvar5.method2();Sleet 2/Snow 2/Fog 3 hvar1.method3();Sleet 3 ivar2.method3();Snow 3 jvar3.method3();Fog 3

31 Solutions to Handout #15 Solutions for letters k through t: LetterCodeOutput kvar4.method3();compiler error lvar5.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