Session 18 Chapter 8: Understanding Inheritance. Recall Exercise 2 From Tuesday It’s very annoying to move a target from the pallet and drop it in the.

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

Introduction to Java 2 Programming
Containers CMPS Reusable containers Simple data structures in almost all nontrivial programs Examples: vectors, linked lists, stacks, queues, binary.
 Specifies a set of methods (i.e., method headings) that any class that implements that interface must have.  An interface is a type (but is not a class).
Session 9 MultiballWorld, Refactoring Ball using Inheritence, and Intro. to CannonWorld.
Georgia Institute of Technology Workshop for CS-AP Teachers Chapter 3 Advanced Object-Oriented Concepts.
Objectives Introduction to Inheritance and Composition (Subclasses and SuperClasses) Overriding (and extending), and inheriting methods and constructors.
C8: Understanding Inheritance. Intuitive description Intuitive: FLORISTS are SHOPKEEPERS, inheriting various shopkeeper behaviors Tension in OOP languages:
CSE341: Programming Languages Lecture 26 Subtyping for OOP Dan Grossman Fall 2011.
1 Inheritance. 2 One class inherits from another if it describes a specialized subset of objects Terminology: inheritschild class subclass –the class.
1 Lecture 06(Abstract Classes)Lecture 9 Abstract Classes Overview  Abstract Classes: A Definition.  Declaring Abstract Classes.  Abstract Methods: A.
© 2006 Pearson Addison-Wesley. All rights reserved4-1 Chapter 4 Data Abstraction: The Walls.
Lecture 18 Review the difference between abstract classes and interfaces The Cloneable interface Shallow and deep copies The ActionListener interface,
Building Java Programs Inner classes, generics, abstract classes reading: 9.6, 15.4,
Chapter 10 Classes Continued
OOP Week 3 1 Object Oriented Programming in Java Monday, Week 3 Interface PinBallTarget OOP Concepts Last Week’s Assignment Arrays Collection Class --
OOP Week 4 1 Object Oriented Programming in Java Monday, Week 4 Last week’s asst. –rating…. This week’s asst. OOP Concepts Inheritance & Substitutability.
CSCI-383 Object-Oriented Programming & Design Lecture 15.
CSSE501 Object-Oriented Development
Subclasses and Subtypes CMPS Subclasses and Subtypes A class is a subclass if it has been built using inheritance. ▫ It says nothing about the meaning.
COP 2800 Lake Sumter State College Mark Wilson, Instructor.
Session 12 Introduction to PinBallGame (Chaper 7).
Specialization and Inheritance Chapter 8. 8 Specialization Specialized classes inherit the properties and methods of the parent or base class. A dog is.
Session 21 Chapter 10: Mechanisms for Software Reuse.
Session 11 Border Layout, using Panels, Introduction to PinBallGame.
Chapter 2 Introducing Interfaces Summary prepared by Kirk Scott.
Session 15 Chapter 8: Understanding Inheritance. Lab Exercise Solution Recall that we needed to know if a mousePress occurred on a target. We tried to.
Instructor: Tasneem Darwish1 University of Palestine Faculty of Applied Engineering and Urban Planning Software Engineering Department Object Oriented.
Chapter 7: Pinball Game Construction Kit. Vectors Example of a “collection class” Must “import java.util.Vector” More flexible than arrays: will grow.
Session 16 Pinball Game Construction Kit:. Pinball Version 1 Replaced the fire button with a mouse event. Multiple balls can be in the air at once. –Uses.
Lecture 12 March 16, The Scope of a Variable What if there are two variables with the same name? –A local or block-local variable can have the same.
Session 19 Chapter 10 – Mechanisms for Software Reuse.
Chapter 14 Abstract Classes and Interfaces. Abstract Classes An abstract class extracts common features and functionality of a family of objects An abstract.
Abstract Classes and Interfaces Chapter 9 CSCI 1302.
Session 13 Pinball Game Construction Kit (Version 3):
Session 22 Chapter 11: Implications of Inheritance.
Session 24 Chapter 12: Polymorphism. Polymorphism polymorphism comes from the Greek root for “many forms” polymorphism is about how we can use different.
CS 151: Object-Oriented Design October 31 Class Meeting Department of Computer Science San Jose State University Fall 2013 Instructor: Ron Mak
Session 25 Test 2 Review. Test 2 Details Tuesday, November 22 in class –(Anybody planning on taking it on Friday?) Closed book Closed notes, except for.
(1) ICS 313: Programming Language Theory Chapter 12: Object Oriented Programming.
BallWorld.java Ball.java A functional walkthrough Part 3: the interaction of objects.
Inheritance CSI 1101 Nour El Kadri. OOP  We have seen that object-oriented programming (OOP) helps organizing and maintaining large software systems.
Inheritance Type/Subtype Relationship. Inheritance Idea: An object B of one type, termed child class, inherits from another object A of another type,
Session 18 Lab 9 Re-cap, Chapter 12: Polymorphism & Using Sound in Java Applications.
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
Quick Review of OOP Constructs Classes:  Data types for structured data and behavior  fields and methods Objects:  Variables whose data type is a class.
CSSE501 Object-Oriented Development. Chapter 10: Subclasses and Subtypes  In this chapter we will explore the relationships between the two concepts.
Java exercise review Lesson 26: Exercise 4. Exercise #4 – a sample solution 1.Write the psudocode and the deployment diagram for what you are planning.
POLYMORPHISM Chapter 6. Chapter Polymorphism  Polymorphism concept  Abstract classes and methods  Method overriding  Concrete sub classes and.
C10, Mechanisms for Software Reuse. Substitutability A variable declared as one type holds a value of another type In Java either: Subclass: allPiles.
Object-Oriented Programming: Polymorphism Chapter 10.
Session 7 More Implications of Inheritance & Chapter 5: Ball World Example.
 Description of Inheritance  Base Class Object  Subclass, Subtype, and Substitutability  Forms of Inheritance  Modifiers and Inheritance  The Benefits.
Lecture 5:Interfaces and Abstract Classes Michael Hsu CSULA.
Session 8 Lab 4 comments, MultiballWorld, Refactoring Ball using Inheritence, and Intro. to CannonWorld.
Lecture 6:Interfaces and Abstract Classes Michael Hsu CSULA.
CSCI 383 Object-Oriented Programming & Design Lecture 15 Martin van Bommel.
Inheritance a subclass extends the functionality of a superclass a subclass inherits all the functionality of a superclass don't reinvent the wheel – "stand.
1 Block1-Unit 3 Using Inheritance Budd Tayseer AL-khdour
A structured walkthrough
Inheritance and Polymorphism
A tree set Our SearchTree class is essentially a set.
Week 6 Object-Oriented Programming (2): Polymorphism
A tree set Our SearchTree class is essentially a set.
Chapter 9 Carrano Chapter 10 Small Java
Border Layout, using Panels, Introduction to PinBallGame
Expanding the PinBallGame
Chapter 10: Mechanisms for Software Reuse
Chapter 6 Inheritance.
Presentation transcript:

Session 18 Chapter 8: Understanding Inheritance

Recall Exercise 2 From Tuesday It’s very annoying to move a target from the pallet and drop it in the wrong place. So, we extended the solution to allow for the targets in the playing field to be moved.

Exercise 2 Solution Recall that we needed to know if a mousePress occurred on a target. We tried to leverage the intersects method of PinBallTarget interface by creating a temporary ball at the point of the mouse press: Ball tempBall = new Ball( e.getX(), e.getY(), 1 ); for ( int j = 0; j < targets.size(); j++ ) { PinBallTarget target=(PinBallTarget) targets.elementAt(j); if ( target.intersects( tempBall ) ) { startPressed = 1; element = target; } // end if } // end for

Opening Exercise 2 Solution We didn’t want to create a PinBall because PinBalls get constructed with motion and a large size. This forced us to change the PinBallTarget interface to accept the more general Ball: public interface PinBallTarget { public boolean intersects( Ball aBall ); public void moveTo ( int x, int y ); public void paint ( Graphics g ); public void hitBy ( PinBall aBall ); } // end PinBallTarget We also have to change the intersects methods in each of the targets It turns out that we could have used a PinBall since it exists for such a short time

Question If you had to pick one word that identifies the key concepts of this course so far, what would it be? Why?

My Answer If you had to pick one word that identifies the key concepts of this course so far, what would it be? Why? –I think I might pick “Inheritance”

Inheritance What? A mechanism for reusing code in an existing class. A mechanism for organizing kinds of objects that have the same implementation. How? Create a class that extends another class. Why? Who wants to rewrite code?? Reuse provides: reliability through continual testing shorter development time ability to build frameworks (don’t call us...) You can quickly build an application for demonstration purposes.

Another Exercise On Page 132, Budd describes how we might implement the class Set as a subclass of class Vector. A Set lets you add an element to it only if the Set doesn’t already contain that element. What messages should a set respond to?

Another Exercise On Page 132, Budd describes how we might implement the class Set as a subclass of class Vector. A Set lets you add an element to it only if the Set doesn’t already contain that element. –addElement( Object ) –removeElement( Object ) –contains( Object ) –isEmpty() –size() If ‘Set extends Vector’, which of these are already in existence? Which are correct?

Another Exercise On Page 132, Budd describes how we might implement the class Set as a subclass of class Vector. A Set lets you add an element to it only if the Set doesn’t already contain that element. –addElement( Object ) –removeElement( Object ) –contains( Object ) –isEmpty() –size() Write the addElement method that we need to complete the Set class.

Another Exercise On Page 132, Budd describes how we might implement the class Set as a subclass of class Vector. A Set lets you add an element to it only if the Set doesn’t already contain that element. –addElement( Object ) –removeElement( Object ) –contains( Object ) –isEmpty() –size() If ‘Set extends Vector’ What other problem(s) do we have?

A possible solution import java.util.Vector; public class Set extends Vector { public Set() { super(); } public void addElement( Object object ) { if ( !contains( object )) super.addElement( object ); } public int indexOf( Object newElement ) { System.out.println("Set.indexOf is not allowed." ); return -1; } public Object elementAt( int index ) { return null; }

Inheritance In one sense, a subclass is an expansion of its superclass. a subclass can add instance variables and methods In another sense, a subclass is a contraction of its superclass. a subclass defines a subset of instances of its superclass In Java, all classes are subclasses, whether we say so or not. By default, any class that does not have an extends clause extends the class Object. Consider our Ball hierarchy: Ball, MovableBall, BoundedBall

public class Ball { private Rectangle location; private Color color; public Ball( int x, int y, int r ) {... } public void paint( Graphics g ) {... } public void setColor( Color newColor ) {... } protected Rectangle region() {... } protected Color color() {... } protected int radius() {... } protected int x() {... } protected int y() {... } protected void moveTo( int x, int y ) {... } } public class MovableBall extends Ball { private double dx; private double dy; public MovableBall( int x, int y, int r ) {... } public void move() {... } public void setMotion( double ndx, double ndy ) {... } protected double xMotion() {... } protected double yMotion() {... } } public class BoundedBall extends MovableBall { private Frame myWorld; public BoundedBall( int x, int y, int r, Frame myWorld ) {... } public void move() {... } }

Inheritance and Substitutability An object X is substitutable for an object Y if we can use X any place we use Y and the client code not know the difference. An example in practice, from the pinball games: The target vector holds any Object. That’s how Java Vectors work. We put Springs, Walls, Holes,..., into the vector. When we retrieve objects from the vector, we treat them as PinBallTargets.

Inheritance and Substitutability Another example in practice, from the cannon games: Our “fire” Button expects to be given an ActionListener that watches for button events. We create FireButtonListener as an implementation of the ActionListener interface. We add a FireButtonListener in place of an ActionListener. What would the alternative be?

Substitutability The common feature in these cases — and the key to substitutability — is that the objects share a common interface. They respond to the same messages. Inheritance and interfaces are mechanisms for ensuring the common interface.

Substitutability So, why write our programs so that they use substitutable objects? extendibility flexibility frameworks that implement a program’s control while allowing programmers to add new objects to the program later Of course, we can achieve these benefits without the use of inheritance and interfaces. But the compiler wouldn’t be able to help us enforce them!

Types of Inheritance Specialization Essentially no new methods in the subclass. Most subclass methods override inherited methods. example: our BoundedBall class common in frameworks

Types of Inheritance Specification Superclass provides responsibility but no behavior. Implement an interface or extend an abstract class. example: our event listeners example: pinball targets private class MouseKeeper extends MouseAdapter { private PinBallTarget element; public void mousePressed ( MouseEvent e ) {... } public void mouseReleased( MouseEvent e ) {... } }

Number - Abstract Class Example Parent class for numeric wrapper classes: Integer, Long, Double, etc. Subclasses must override abstract methods public abstract class Number { public abstract int intValue(); public abstract long longValue(); public abstract float floatValue(); public abstract double doubleValue() public byte byteValue() {return (byte) intValue;} public short shortValue() { return (short) intValue(); } } // end Number

Types of Inheritance Extension Subclass uses most or all inherited methods as-is. Subclass adds new behavior and methods. example: our MovableBall class

Types of Inheritance Combination A class inherits from two or more classes. This is called multiple inheritance. Some OOP languages provide it (C++). Some don’t (Java, Smalltalk). Java does support combination through interfaces. example: Budd’s Hole class class Hole extends Ball implements PinBallTarget { public Hole( int x, int y ) {... } public boolean intersects( Ball aBall ) {... } public void hitBy ( Ball aBall ) {... } }

Other Types of Inheritance Limitation The subclass primarily has methods that override inherited methods. to restrict a behavior (example: Square extends Rectangle) to remove a behavior (example: Set extends Vector) Limitation violates the principle of substitutability.

Other Types of Inheritance Construction The subclass reuses a class because it provides needed functionality but it is not necessarily true that an instance of the subclass is an instance of the superclass. example: Java’s Stack class (ouch!) Construction may violate the principle of substitutability. JUST DON’T DO IT.