11/20/2006 CMSC 131 Fall 2006Rance Cleaveland©2006 Univeristy of MarylandLecture 35:PolymorphismLast time:1. Method overriding2. Shadowing3. Access issues in inheritanceToday:1. Project #7 assigned2. Object3. Polymorphism and abstract methods4. Upcasting / downcastingCMSC 131 Fall 2006Rance Cleaveland©2006 University of Maryland1Project #7 Assigned! Project due Wednesday, 11/29 at 11 pm Project is closed You must complete the project by yourself Assistance can only be provided by teaching assistants (TAs) and instructors You must not look at other students' code Start now! Read entire assignment from beginning to end before starting to code Check out assignment now from CVS Follow the instructions exactly, as much of grading is automatedCMSC 131 Fall 2006Rance Cleaveland©2006 University of Maryland2Recap Inheritance occurs when one class (derived class, subclass) is defined from another class (base / parent class, superclass). To derive a class D from a base class B, use:public class D extends B { … } Derived class inherits all instance variables, methods from base class. It can also define new instance variables, methods In derived-class constructor, super( … ) can be used to invoke constructor from base class Derived class can explicitly refer to entities from base class using super, e.g. super.toString( ) Polymorphism: object in derived class can be used anywhere base class is expected (a Student “is a” Person!) Derived class can override base-class methods (and variables) final can be used to disallow overriding Java uses late binding to determine which version of method to use protected modifier exposes declarations to subclasses (and package)CMSC 131 Fall 2006Rance Cleaveland©2006 University of Maryland3Object Recall: inheritance induces “is-a” hierarchy on classes Undergrad “is-a” Student Student “is-a” Person etc. Person “is-a” ….? Person “is-a”(n) ObjectPersonStudent Faculty AdministratorUndergrad GradStudent Instructor Professor……PersonStudent FacultyObjectCMSC 131 Fall 2006Rance Cleaveland©2006 University of Maryland4More on Object Special class at top of class inheritance hierarchy Defined in java.lang (so available in every program) Every class is derived (either directly or indirectly) from Object If a class is not derived from anything, it is automatically derived from Object e.g.public class Foo { …}is equivalent topublic class Foo extends Object {…}CMSC 131 Fall 2006Rance Cleaveland©2006 University of Maryland5Structure of Object No instance variables A number of methods, including: toString() equals (Object o)Note: parameter to equals has type Object, so any object can be an argument These methods can (and usually should) be overridden Class hierarchy:ObjectPersonStudent FacultyUndergrad GradStudent Instructor ProfessorString NumberInteger FloatBooleanDoubleYour classesare all hereThe classes from the Javaclass library are here.Defined in java.lang.CMSC 131 Fall 2006Rance Cleaveland©2006 University of Maryland6Polymorphism and Inheritance Recall Objects in derived classes can be used wherever objects in base classes are needede.g. Person p = new Student (); Java uses late binding to determine which version of overridden method to use This means reference variables like p are polymorphic Object referred to by p may be from any class derived from Person An object is not modified when assigned to p; it retains its original form (e.g. Student in above case)CMSC 131 Fall 2006Rance Cleaveland©2006 University of Maryland7Polymorphism and Arrays Example: Create an array of various university people and printPerson[ ] list = new Person[3];list[0] = new Person("Col. Mustard","000-00-0000");list[1] = new Student ("Ms. Scarlet","111-11-1111", 1998, 3.2);list[2] = new Faculty ("Prof. Plum","222-22-2222",1981);for (int i = 0; i < list.length; i++)System.out.println( list[i].toString( ) ); What type is list[i]? It can be a reference to any object that is derived from Person Late binding ensures the appropriate toString() will be calledCMSC 131 Fall 2006Rance Cleaveland©2006 University of Maryland8An Inheritance Example Goal: picture-drawing program Picture is array of different shapes Program should draw each shape on screen Desiderata Shapes to handle initially are circles, rectangles Want to leave door open for new shapes in future Drawing shapes depends on kind of shape (drawing a rectangle different from drawing a circle)CMSC 131 Fall 2006Rance Cleaveland©2006 University of Maryland9Class Design Use inheritance hierarchy for shapes Base class (Shape) includes Color field (as in Lecture #33) drawMe() method for drawing shape Derived classes will override drawMe()ShapeCircle RectangleTriangleRight-Triangle Equilateral-TriangleBase class includes:private int colorpublic void setColor(int c)public int getColor()public void drawMe()Triangle class, subclassesmay be added laterCMSC 131 Fall 2006Rance Cleaveland©2006 University of Maryland10Picture Drawing Picture: array shapes of type Shape[] To draw picture, invoke drawMe() for each shape:Shape[ ] shapes = new Shape[…];shapes[0] = new Circle( … );shapes[1] = new Rectangle( … );…for ( int i = 0; i < shapes.length; i++ )shapes[i].drawMe(); Note importance of late binding for this strategy!Heap:shapes[0][1][2]…(a Circle object)(a Rectangle object)…CMSC 131 Fall 2006Rance Cleaveland©2006 University of Maryland11Java Code Assume: class Point storing x, y coordinates Code layoutpublic class Shape {private int color; // Color of shape…public void drawMe () { … }}public class Circle extends Shape {private double radius; // Radius of circleprivate Point center; // Center of circle…public void drawMe () { … } // Draws a circle}public class Rectangle extends Shape {private Point upperLeft; // Upper left cornerprivate Point lowerRight; // Lower right corner…public void drawMe () { … } // Draws a rectangle}CMSC 131 Fall 2006Rance Cleaveland©2006 University of Maryland12Abstract Methods Problem: how to implement drawMe() method for Shape?Shape class is for generic shapes … insufficient info to draw Could just do something ad hoc in implementation: Raise an exception Do nothing Bad idea! Point of drawMe() method is to override it in derived classes If
View Full Document