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? http://java.sun.com/j2se/1.4.2/docs/api/java/util/Vector.html 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.