29-July-2002cse142-14-Inheritance © 2002 University of Washington1 Inheritance CSE 142, Summer 2002 Computer Programming 1

Slides:



Advertisements
Similar presentations
Chapter 13 Abstraction and inheritance. This chapter discusses n Implementing abstraction. u extension u inheritance n Polymorphism/dynamic binding. n.
Advertisements

Basic Object-Oriented concepts. Concept: An object has behaviors In old style programming, you had: –data, which was completely passive –functions, which.
1 Chapter 6: Extending classes and Inheritance. 2 Basics of Inheritance One of the basic objectives of Inheritance is code reuse If you want to extend.
CS 106 Introduction to Computer Science I 04 / 11 / 2008 Instructor: Michael Eckmann.
Objectives Introduction to Inheritance and Composition (Subclasses and SuperClasses) Overriding (and extending), and inheriting methods and constructors.
SE-1020 Dr. Mark L. Hornick 1 Inheritance and Polymorphism: Abstract Classes The “not quite” classes.
Polymorphism & Methods COMP204 Bernhard Pfahringer (with lots of input from Mark Hall) poly + morphos (greek) “many forms”
CS 106 Introduction to Computer Science I 11 / 26 / 2007 Instructor: Michael Eckmann.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Inheritance and Polymorphism.
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.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
Encapsulation, Inheritance & Interfaces CSE 115 Spring 2006 February 27, March 1 & 3, 2006.
CS 106 Introduction to Computer Science I 04 / 16 / 2010 Instructor: Michael Eckmann.
Fall 2007CS 2251 Inheritance and Class Hierarchies Chapter 3.
CS 106 Introduction to Computer Science I 11 / 15 / 2006 Instructor: Michael Eckmann.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
1 Inheritance and Polymorphism. 2 Motivations Suppose you will define classes to model circles, rectangles, and triangles. These classes have many common.
1 Evan Korth New York University Inheritance and Polymorphism Professor Evan Korth New York University.
Chapter 10: Inheritance and Polymorphism
Computer Science I Inheritance Professor Evan Korth New York University.
(c) University of Washington03-1 CSC 143 Java Inheritance Reading: Ch. 10.
CS 106 Introduction to Computer Science I 04 / 13 / 2007 Friday the 13 th Instructor: Michael Eckmann.
Polymorphism & Interfaces
Chapter 11 Inheritance and Composition. Chapter Objectives Learn about inheritance Learn about subclasses and superclasses Explore how to override the.
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
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.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
What is inheritance? It is the ability to create a new class from an existing class.
Liang, Introduction to Java Programming, Ninth Edition, (c) 2013 Pearson Education, Inc. All rights reserved. 1 Chapter 11 Inheritance and Polymorphism.
CSC 205 Java Programming II Polymorphism. Topics Polymorphism The principle of substitution Dynamic binding Object type casting Abstract class The canonical.
CSC 142 Computer Science II Zhen Jiang West Chester University
Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Inheritance and Polymorphism.
RIT Computer Science Dept. Goals l Inheritance l Modifiers: private, public, protected l Polymorphism.
Chapter 3 Inheritance and Polymorphism Goals: 1.Superclasses and subclasses 2.Inheritance Hierarchy 3.Polymorphism 4.Type Compatibility 5.Abstract Classes.
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.,
Inheritance and Access Control CS 162 (Summer 2009)
Inheritance. Inheritance - Introduction Idea behind is to create new classes that are built on existing classes – you reuse the methods and fields and.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2007 Pearson Education, Inc. All rights reserved Chapter 9 Inheritance and.
Object Oriented Programming
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
1 COSC2007 Data Structures II Chapter 9 Class Relationships.
Polymorphism & Methods COMP206 Geoff Holmes & Bernhard Pfahringer (these slides: lots of input from Mark Hall) poly + morphos (greek) “many forms”
Application development with Java Lecture 21. Inheritance Subclasses Overriding Object class.
Coming up: Inheritance
Java Programming: From Problem Analysis to Program Design, 3e Chapter 11 Inheritance and Polymorphism.
Inheritance and Subclasses CS 21a. 6/28/2004 Copyright 2004, by the authors of these slides, and Ateneo de Manila University. All rights reserved L16:
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.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
(c) University of Washington06-1 CSC 143 Java Inheritance Tidbits.
FEN 2014UCN Teknologi/act2learn1 Object-Oriented Programming “ The Three Pillars of OOP”: Encapsulation Inheritance Polymorphism The Substitution Principle.
1 / 71 COP 3503 FALL 2012 SHAYAN JAVED LECTURE 4 Programming Fundamentals using Java 1.
Basic Object-Oriented concepts. Concept: Classes describe objects Every object belongs to (is an instance of) a class An object may have fields –The class.
OOP in Java : © W. Milner 2005 : Slide 1 Java and OOP Part 3 – Extending classes.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
Modern Programming Tools And Techniques-I
Sections Inheritance and Abstract Classes
Week 4 Object-Oriented Programming (1): Inheritance
Road Map Inheritance Class hierarchy Overriding methods Constructors
Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is new code that reuses old code. Polymorphism.
MSIS 670 Object-Oriented Software Engineering
Week 6 Object-Oriented Programming (2): Polymorphism
Inheritance Inheritance is a fundamental Object Oriented concept
Object Oriented Programming
Chapter 14 Abstract Classes and Interfaces
Presentation transcript:

29-July-2002cse Inheritance © 2002 University of Washington1 Inheritance CSE 142, Summer 2002 Computer Programming 1

29-July-2002cse Inheritance © 2002 University of Washington2 Readings and References Reading »Sections 14.1 and 14.2, An Introduction to Programming and Object Oriented Design using Java, by Niño and Hosch Other References »Sections Object-Oriented Programming Concepts and Classes and Inheritance of the Java tutorial »

29-July-2002cse Inheritance © 2002 University of Washington3 Relationships between classes Classes can be related via composition »This is often referred to as the “has-a” relationship »eg, a Car has a list in an ArrayList of Shapes Classes can also be related via inheritance »This is often referred to as the “is-a” relationship »eg, a Triangle is a PolyShape

29-July-2002cse Inheritance © 2002 University of Washington4 Composition Vs. Inheritance The “has-a” relationship is composition The “is-a” relationship is inheritance Prefer composition to inheritance Beware of inheritance graphs that are either very wide or very deep »very wide means that you are perhaps not abstracting enough at the top layer »very deep means that you are adding only a little functionality at each layer and making fine distinctions that may not survive the test of time

29-July-2002cse Inheritance © 2002 University of Washington5 Car has a list of Shapes Car ArrayList myShapes int cornerX int cornerY int deltaY int deltaX etc ArrayList int size item 0 item 1 item 2 etc Oval Rectangle Oval

Triangle is a PolyShape is a

29-July-2002cse Inheritance © 2002 University of Washington7 Why use inheritance? Code simplification »Avoid doing the same operation in two places »Avoid storing “matching state” in two places Code simplification »We can deal with objects based on their common behavior, and don’t need to have special cases for each subtype Code simplification »Lots of elegant code has already been written - use it, don’t try to rewrite everything from scratch

29-July-2002cse Inheritance © 2002 University of Washington8 Why use inheritance? Example: Shapes »What is some behavior common to all shapes? movement, intersection »What are some attributes common to all shapes? size, location, color We defined behaviors that a Shape must have when we discussed the Shape interface But even with an interface defined, we still need implementations for each method

29-July-2002cse Inheritance © 2002 University of Washington9 The Shape interface From OvalSlider.java OvalSlider doesn’t care about the special characteristics of an Oval, it only cares that an Oval can do the things that a good Shape should be able to do /** the Shape that we are moving around on the screen */ private Shape theShape; void addTo(GWindow gw) Rectangle getBoundingBox() int getCenterX() int getCenterY() java.awt.Color getColor() int getHeight() int getWidth() int getX() int getY() uwcse.graphics.InternalGWindow currentWindow() boolean intersects(Shape other) void moveBy(int deltaX, int deltaY) void moveTo(int x, int y) void paint(java.awt.Graphics g) void recordWindow(uwcse.graphics.InternalGWindow gw) void removeFromWindow() void rotateAround(int pivotX, int pivotY, double degrees) void setColor(java.awt.Color c)

29-July-2002cse Inheritance © 2002 University of Washington10 Why use inheritance? Sometimes it takes several levels of abstraction to get to concrete objects »a Triangle is a PolyShape, which is a ShapeImpl, which is an Object. At each of these levels, there might be behavior to “factor out” or abstract away. All Shapes must implement similar methods »we want to do “ int x = blob.getX() ” »if both Triangles and Ovals implement this the same way, we can implement getX() in one base class, and use it in the subclasses instead of rewriting it each time

Triangle constructors and methods

29-July-2002cse Inheritance © 2002 University of Washington12 Syntax of inheritance Specify inheritance relationship using extends »this is just like we did with interfaces public abstract class ShapeImpl implements Shape { protected Rectangle boundingBox; … public int getX() { return boundingBox.getX(); } public abstract class PolyShape extends ShapeImpl { private int npoints; public class Triangle extends PolyShape {

29-July-2002cse Inheritance © 2002 University of Washington13 Reduce the need for duplicated code Remember our collection of pets? »Dog has getMealSize() and eat(double w) methods »Cat has getMealSize() and eat(double w) methods »and they are implemented exactly the same way We can define a class named BasicAnimal that implements these methods once, and then the subclasses can extend it and add their own implementations of other methods if they like

29-July-2002cse Inheritance © 2002 University of Washington14 BasicAnimal class

29-July-2002cse Inheritance © 2002 University of Washington15 Dog as a subclass of BasicAnimal

29-July-2002cse Inheritance © 2002 University of Washington16 Using the superclass constructor Constructor of the superclass is called to do much (or all) of the initialization for the subclass public class BasicAnimal implements Animal { public BasicAnimal(String theName,double serving,double weight) { name = theName; mealSize = serving; currentWeight = weight; System.out.println("Created "+name); } public class Dog extends BasicAnimal { public Dog(String theName) { super(theName,0.5,20); } public Dog(String theName,double serving,double weight) { super(theName,serving,weight); }

29-July-2002cse Inheritance © 2002 University of Washington17 this() and super() as constructors You can use an alias to call another constructor »super(...) to call a superclass constructor »this(…) to call another constructor from same class The call to the other constructor must be the first line of the constructor »If neither this() nor super() is the first line in a constructor, a call to super() is inserted automatically by the compiler. This call takes no arguments. If the superclass has no constructor that takes no arguments, the class will not compile.

29-July-2002cse Inheritance © 2002 University of Washington18 Overriding methods Overriding methods is how a subclass refines or extends the behavior of a superclass method Manager and Executive classes extend Employee How do we specify different behavior for Managers and Executives? »Employee: double pay() {return hours*rate + overtime*(rate+5.00);} »Manager: double pay() {return hours*rate;} »Executive: double pay() {return salary + bonus;}

29-July-2002cse Inheritance © 2002 University of Washington19 Overriding methods public class Employee { // other stuff public float pay() { return hours*rate + overtime*(rate+5.00); } public class Manager extends Employee { // other stuff public float pay() { return hours*rate; }

29-July-2002cse Inheritance © 2002 University of Washington20 // in superclass public void pay() {...} // in subclass public void pay() {...} // valid private void pay() {...} // invalid Overriding rules A method cannot be made more private than the superclass method it overrides

29-July-2002cse Inheritance © 2002 University of Washington21 Overriding rules A method’s return type and parameters must match those in the overridden superclass method exactly in order to override it. // in superclass public int pay(int hours) {} // in subclass public int pay(int b) {} // okay, overrides public long pay(int b) {} // compile error

29-July-2002cse Inheritance © 2002 University of Washington22 instanceof Used to test an object for class membership Good way to ensure that a cast will succeed Tests for a relationship anywhere along the hierarchy »Also tests whether a class implements an interface What class must represent for the following expression to be true always? if (v instanceof ) { … } if (bunch.get(i) instanceof Dog) {…}

29-July-2002cse Inheritance © 2002 University of Washington23 instanceof example with interface ArrayList onStage = theStage.getActors(); for (int i=0; i<onStage.size(); i++) { if (onStage.get(i) instanceof ClickableActor) { ClickableActor clickee = (ClickableActor)onStage.get(i); if (clickee.intersects(cursor)) { clickee.doClickAction(theStage); if (clickee == runButton) { if (runButton.isEnabled()) { theStage.animate(); } else { theStage.quitAnimation(); }