18 - Abstract Classes, Polymorphism, and Inheritance 1 Abstract Classes, Polymorphism, and Inheritance Barb Ericson Georgia Institute of Technology Dec.

Slides:



Advertisements
Similar presentations
1 Drawing C Sc 335 Object-Oriented Programming and Design Rick Mercer.
Advertisements

Systems Analysis and Design 8th Edition
AbstractClassesInterfacesPolymorphism1 Abstract Classes, Interfaces, Polymorphism Barb Ericson Georgia Tech April 2010.
Georgia Institute of Technology Workshop for CS-AP Teachers Chapter 3 Advanced Object-Oriented Concepts.
Slides 4/22 COP Topics Final Exam Review Final Exam The final exam is Friday, April 29 th at 10:00 AM in the usual room No notes, books, calculators,
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,
Design Patterns in Java Appendix D UML at a Glance Summary prepared by Kirk Scott 1.
1 Lecture 06(Abstract Classes)Lecture 9 Abstract Classes Overview  Abstract Classes: A Definition.  Declaring Abstract Classes.  Abstract Methods: A.
ObjectDraw and Objects Early Chris Nevison Barbara Wells.
©The McGraw-Hill Companies, Inc. Permission required for reproduction or display. 4 th Ed Chapter N - 1 Chapter 13 Polymorphism is-a relationships Interfaces.
CS221 - Computer Science II Polymorphism 1 Inheritance "Question: What is the object oriented way of getting rich? Answer: Inheritance.“ “Inheritance is.
Abstraction: Polymorphism, pt. 1 Abstracting Objects.
CSSE501 Object-Oriented Development
(c) University of Washington03-1 CSC 143 Java Inheritance Reading: Ch. 10.
Chapter 6 Class Inheritance F Superclasses and Subclasses F Keywords: super F Overriding methods F The Object Class F Modifiers: protected, final and abstract.
CISC6795: Spring Object-Oriented Programming: Polymorphism.
Inheritance and Class Hierarchies Ellen Walker CPSC 201 Data Structures Hiram College.
CPSC1301 Computer Science 1 Chapter 11 Creating Classes part 1.
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.
CreatingClasses-part11 Creating Classes part 1 Barb Ericson Georgia Institute of Technology Dec 2009.
An Introduction to Java Chapter 11 Object-Oriented Application Development: Part I.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
Georgia Institute of Technology Creating Classes part 1 Barb Ericson Georgia Institute of Technology Oct 2005.
Inheritance in the Java programming language J. W. Rider.
Systems Analysis & Design 7 th Edition Chapter 5.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
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.
Object Oriented Software Development
Appendix D UML at a Glance Summary prepared by Kirk Scott 1.
CS2110: SW Development Methods Inheritance in OO and in Java Part 2: Topics: Forms of inheritance Interfaces in Java.
JAVA: An Introduction to Problem Solving & Programming, 6 th Ed. By Walter Savitch ISBN © 2012 Pearson Education, Inc., Upper Saddle River,
CreatingSubclasses1 Barb Ericson Georgia Institute of Technology Dec 2009.
1 Class Diagrams. 2 Overview Class diagrams are the most commonly used diagrams in UML. Class diagrams are for visualizing, specifying and documenting.
Georgia Institute of Technology Creating Classes part 4 Barb Ericson Georgia Institute of Technology May 2006.
CreatingClasses-SlideShow-part41 Creating Classes part 4 Barb Ericson Georgia Institute of Technology Dec 2009.
CreatingClasses-SlideShow-part31 Creating Classes part 3 Barb Ericson Georgia Institute of Technology Dec 2009.
M1G Introduction to Programming 2 3. Creating Classes: Room and Item.
CHAPTER 14 Classes, Objects, and Games XNA Game Studio 4.0.
Method Overriding Remember inheritance: when a child class inherits methods, variables, etc from a parent class. Example: public class Dictionary extends.
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:
Chapter 11: Advanced Inheritance Concepts. Objectives Create and use abstract classes Use dynamic method binding Create arrays of subclass objects Use.
Georgia Institute of Technology More on Creating Classes part 3 Barb Ericson Georgia Institute of Technology Nov 2005.
Subclassing, pt. 2 Method overriding, virtual methods, abstract classes/methods COMP 401, Fall 2014 Lecture 9 9/16/2014.
Interfaces, Abstract Classes, and Polymorphism. What Is an Interface? An interface is the set of public methods in a class Java provides the syntax for.
SourceAnatomy1 Java Source Anatomy Barb Ericson Georgia Institute of Technology July 2008.
Terms and Rules II Professor Evan Korth New York University (All rights reserved)
Author: DoanNX Time: 45’.  OOP concepts  OOP in Java.
Georgia Institute of Technology Comic Strip Analysis and Design Inheritance, Abstract Classes, and Polymorphism part 2 Barb Ericson Georgia Institute of.
Georgia Institute of Technology Comic Strip Analysis and Design Inheritance, Abstract Classes, and Polymorphism part1 Barb Ericson Georgia Institute of.
CSCI-383 Object-Oriented Programming & Design Lecture 17.
Notices Assn 2 is due tomorrow, 7pm. Moodle quiz next week – written in the lab as before. Everything up to and including today’s lecture: Big Topics are.
Georgia Institute of Technology Workshop for CS-AP Teachers Chapter 3 Advanced Object-Oriented Concepts.
Georgia Institute of Technology More on Creating Classes Barb Ericson Georgia Institute of Technology June 2006.
Lecture 10 – Polymorphism Nancy Harris with additional slides Professor Adams from Lewis & Bernstein.
Inheritance a subclass extends the functionality of a superclass a subclass inherits all the functionality of a superclass don't reinvent the wheel – "stand.
JAVA: An Introduction to Problem Solving & Programming, 5 th Ed. By Walter Savitch and Frank Carrano. ISBN © 2008 Pearson Education, Inc., Upper.
Object-Oriented Design
Creating and Modifying Text part 2
Interfaces and Inheritance
Barb Ericson Georgia Institute of Technology May 2006
Arrays versus ArrayList
Workshop for CS-AP Teachers
Barb Ericson Georgia Institute of Technology Oct 2005
Workshop for Programming And Systems Management Teachers
Workshop for Programming And Systems Management Teachers
Inheritance and Polymorphism
More on Creating Classes
Creating and Modifying Text part 3
More on Creating Classes part 3
Presentation transcript:

18 - Abstract Classes, Polymorphism, and Inheritance 1 Abstract Classes, Polymorphism, and Inheritance Barb Ericson Georgia Institute of Technology Dec 2010

18 - Abstract Classes, Polymorphism, and Inheritance 2 Learning Goals See examples of object-oriented analysis and design Demonstrate the need for abstract classes and abstract methods Give a detailed example of polymorphism Show how to use inheritance to pull out a common parent class Give an example of using a protected method Explain the purpose of an interface and show one is used

What makes Java object-oriented? Has encapsulation –Objects and classes Has inheritance –Object fields and methods are inherited from a parent class Has polymorphism –The method that is called at run-time depends on the run-time type of the object 18 - Abstract Classes, Polymorphism, and Inheritance 3

Is Alice Object-Oriented? It does have encapsulation –Objects and classes It does not really support inheritance –You can rename an object in the object tree and save it out as a new class –But, this isn't really inheritance. It is just copying methods to the new class It does not really support polymorphism –Alice methods can't be overriden 18 - Abstract Classes, Polymorphism, and Inheritance 4

Object-Oriented Analysis Software engineers do analysis to determine –What objects are needed? What data (fields) and what behaviors (methods) do the objects need? –How are the objects classified (the classes)? –What are the relationships between the classes? 18 - Abstract Classes, Polymorphism, and Inheritance 5

Example If you were creating software to handle –Student registration You would need to understand –Students, Courses, Teachers, –Classrooms, Class Periods (or Sections) –The diagnosis of a stroke You would need to understand –Signs and symptoms, –Patients, –Doctors, –Tests, –Findings, 18 - Abstract Classes, Polymorphism, and Inheritance 6

7 What do we mean by a comic strip? What parts does it have? What things should you be able to find out about one?

18 - Abstract Classes, Polymorphism, and Inheritance 8 A Comic Strip Has a name and an author Typically has 4 panels, but can have more or less The Comic Strip: Pearls Before Swine

18 - Abstract Classes, Polymorphism, and Inheritance 9 A Comic Panel Has a picture And one or more speech balloons

18 - Abstract Classes, Polymorphism, and Inheritance 10 ComicStrip Class Will display a comic strip with one or more ComicPanel’s in it. Modify the main method to create your own comic strip –You can use picture methods to make a black and white comic or one that looks like someone drew it in pencil

18 - Abstract Classes, Polymorphism, and Inheritance 11 When to Use Inheritance? Should a comic panel have a picture as a field or inherit from the Picture class? It depends if they are both kind of pictures Does it make sense to use a comic panel anytime you would use a picture? A child inherits all the fields and methods of the parent class –So don't use inheritance if you just want access to some methods and/or fields –If you aren't sure use a field instead of inheritance

Examples of Class Relationships Is a Polar Bear a kind of Bear? –Yes, you can substitute one for the other –This is a "is-a" or "is-a-type-of" relationship (inheritance) Shown with a triangle Is a circus a type of bear? –No, you can't substitute a bear for a circus –This is a "has-a" relationship (association) Shown with a straight line 18 - Abstract Classes, Polymorphism, and Inheritance 12

18 - Abstract Classes, Polymorphism, and Inheritance 13 A Speech Balloon Is a rounded rectangle or ellipse with text (words) in it Has a tail that indicates who is speaking –The tail is shown as a triangle from the bottom of the rounded rectangle to the speaker

What else do we need? A comic strip should be able to show itself A comic panel needs –The picture –The speech balloons A speech balloon needs –The upper left corner for the ellipse –The message to draw –The end point for the triangle that points to the speaker 18 - Abstract Classes, Polymorphism, and Inheritance 14

18 - Abstract Classes, Polymorphism, and Inheritance 15 A UML Class Diagram Shows the design for an object-oriented solution –Shows each class as a rectangular box May include the fields and methods –Shows the relationships between objects of the classes Has a (association) Is a (inheritance)

Translating from UML to Java Associations may become fields –ComicPanel The numbers on associations mean the number of objects of one class associated with an object of the other class –A ComicStrip has 4 Comic Panels The 0* means zero to many –A ComicPanel can have 0 to many SpeechBalloons public class ComicStrip extends JPanel { ////////////////// fields /////////////////////// private String name; private String author; private ComicPanel[] panelArray = null; } 18 - Abstract Classes, Polymorphism, and Inheritance 16

18 - Abstract Classes, Polymorphism, and Inheritance 17 Thought Balloons Are like speech balloons –But they show what a character is thinking, not saying –Use circles to connect balloon to thinker The Comic Strip: Ben

18 - Abstract Classes, Polymorphism, and Inheritance 18 How to Handle Thought Balloons? We could copy the class for speech balloon and save it out with a new name –And change everywhere that has Speech to Thought –But what if we later want to add something to both classes? We would have to add it in both classes –Also, how would we handle the ComicPanel? Would it have 0 or more SpeechBalloons and 0 or more ThoughtBalloons?

18 - Abstract Classes, Polymorphism, and Inheritance 19 How to Handle Thought Balloons? We could make a new class ThoughtBalloon –As a subclass of SpeechBalloon Since they are very similar But, is this right? –Is a ThoughtBalloon a kind of SpeechBalloon? ComicStrip author name ComicPanel SpeechBalloon upperLeft tailEnd message 1* 0* Picture 1 ThoughtBalloon

18 - Abstract Classes, Polymorphism, and Inheritance 20 Be Careful with Inheritance! Only use it when the child is really of the same type of thing as the parent –Not when they just have some similar fields or methods Instead pull out a common parent class –And have both SpeechBalloon and ThoughtBalloon inherit from it Pull out all common fields and methods –And put them in the common parent class This is also called generalization

18 - Abstract Classes, Polymorphism, and Inheritance 21 Generalization Move common fields and methods into a parent class –And let the children classes inherit the fields and methods –Easier to maintain than copying fields and methods –Better than using inheritance when the child isn’t really a kind of parent –Makes it easier to add new children classes

18 - Abstract Classes, Polymorphism, and Inheritance 22 TextBalloons What should a text balloon know how to do? –It should know how to draw itself It will need a graphics context –Used to do the drawing Add the draw method to the UML class diagram TextBalloon upperLeft tailEnd Message draw(Graphics g)

18 - Abstract Classes, Polymorphism, and Inheritance 23 Abstract Class Can we draw just a text balloon? –What would we draw? We could draw the balloon and text What kind of tail would it have? We need to know what type of text balloon it is in order to draw the tail –Which we will only know at run-time Can’t predict what will be needed So TextBalloon is an abstract class –One that you can not create an object from –You can only inherit from it public abstract class TextBalloon

18 - Abstract Classes, Polymorphism, and Inheritance 24 Try it Try to create a TextBalloon object using the interactions pane in DrJava –Use the constructor that takes a upper left point (java.awt.Point), a width, the point of the tail (java.awt.Point) and a string. import java.awt.Point; TextBalloon balloon = new TextBalloon(new Point (23,33),100,new Point(50,40),”Hi”); What error do you get?

Abstract Methods Abstract classes often have one or more abstract methods –They don't have to have any To make a method abstract –Add the abstract keyword after the visibility and before the return type –The declaration ends in a semicolon Abstract methods can't have a method body visibility abstract returnType methodName(parameterList); public abstract void drawTail(paramList); 18 - Abstract Classes, Polymorphism, and Inheritance 25

What visibility should drawTail use? The abstract method drawTail needs to be overriden by subclasses –We can use public visibility But, this means any class has access –We can't use private visibility You can't override private methods –We could use protected visibility Means the subclasses and classes in the same package have access –But, this means you should really put your classes in packages to restrict access 18 - Abstract Classes, Polymorphism, and Inheritance 26

18 - Abstract Classes, Polymorphism, and Inheritance 27 Exercise Run the main method in ComicPanel to see an example with both a speech balloon and a thought balloon Modify the main method to create your own comic panel with a speech balloon and a thought balloon

18 - Abstract Classes, Polymorphism, and Inheritance 28 Polymorphism Means many forms Means that the method that is executed depends on the type of the object –Often the method is determined by the type of the object at run- time –This is called dynamic or run-time binding TextBalloon upperLeft tailEnd Message drawTail() ThoughtBalloon drawTail() SpeechBalloon drawTail()

18 - Abstract Classes, Polymorphism, and Inheritance 29 Adding a TextBalloon to a ComicPanel Notice that ComicPanel has add(TextBalloon textBalloon) –Adds it to a list of text balloons The method will be called with both SpeechBalloon and ThoughtBalloon –They are both types of TextBalloon so there is no problem with this Called Upcasting TextBalloon upperLeft tailEnd Message drawTail() ThoughtBalloon drawTail() SpeechBalloon drawTail()

18 - Abstract Classes, Polymorphism, and Inheritance 30 Run-time Binding of Methods In getFinalPicture() –Each element of the textBalloonList is told to draw And in draw each is told to drawTail() –What method is called for each of the two types of TextBalloons? The SpeechBalloon The ThoughtBalloon

18 - Abstract Classes, Polymorphism, and Inheritance 31 Finding the draw method The Java Virtual Machine will start looking for a draw method –In the object that defines the class that created the current object Each object keeps a reference to the class that created it –Can get this with getClass() –If the method isn’t found it will try the parent of the class that created the object –And so on up the inheritance tree until the method is found It will be found or the code wouldn’t have compiled –draw will be found in TextBalloon

18 - Abstract Classes, Polymorphism, and Inheritance 32 Finding the drawTail method The draw method calls drawTail –Again the Java virtual machine will look for the method starting with the class that created the object the method was invoked on So for a SpeechBalloon object it will find it in SpeechBalloon And for a ThoughtBalloon object it will find it in ThoughtBalloon

18 - Abstract Classes, Polymorphism, and Inheritance 33 How it works

18 - Abstract Classes, Polymorphism, and Inheritance 34 Exercise There are other kinds of text balloons –Some speech balloons only have a line to the speaker, not a triangle. –Some speech balloons don’t draw the outline of the balloon in black. –Some thought balloons use a cloud to enclose the text. –A scream balloon has bold text and a spiny outline with a flash like tail. It indicates the character is screaming. –Some speech balloons have a black background and white text Pick at least one of these and implement it. –Present what you did and why

An Application for Drawing Shapes What if you want to create an application that allows you to draw shapes –That can be defined by two points? Rectangle Oval Line –What classes do you need? 18 - Abstract Classes, Polymorphism, and Inheritance 35

You might start with this Classes for Rectangle, Oval, and Line –Need 2 points There is a Point class in Java that you can use to represent a 2- dimensional point –Need to be able to draw Is there a common parent class here? 18 - Abstract Classes, Polymorphism, and Inheritance 36

Rectangle, Oval, and Line are Shapes We can pull out a common parent class –Shape Each shape has –Two points that define it –A draw method to draw the shape But, can we create just a shape object or draw it? –No, Shape needs to be an abstract class With an abstract draw method 18 - Abstract Classes, Polymorphism, and Inheritance 37

Code for Shape class Abstract class Has fields for the two points Can have constructors Can have other methods Has an abstract draw method public abstract class Shape extends Object { protected Color color = Color.black; // color protected Point p1 = new Point(); // first point protected Point p2 = new Point(); // second point /* constructors */ /* methods */ public abstract void draw(Graphics g); } 18 - Abstract Classes, Polymorphism, and Inheritance 38

Code for Rectangle (draw method) public class Rectangle extends Shape { // … constructors /** Draw the shape g the graphics context on which to draw */ public void draw(Graphics g) { // set the color g.setColor(color); // draw the rectangle given the top left point and width // and height g.drawRect(getMinX(),getMinY(),getWidth(),getHeight()); } 18 - Abstract Classes, Polymorphism, and Inheritance 39

Code for Oval Class (draw method) public class Oval extends Shape { // … constructors /** Draw the shape g the graphics context on which to draw */ public void draw(Graphics g) { // set the color g.setColor(color); // draw the shape given the top left corner of the enclosing // rectangle and the width and height g.drawOval(getMinX(),getMinY(),getWidth(),getHeight()); } 18 - Abstract Classes, Polymorphism, and Inheritance 40

Why use polymorphism? Allows you to create one parent class –And many subclasses that override inherited methods Often abstract methods –Easy to add new classes They just need to inherit from the common parent And provide the method or methods –You don't need to modify working code Which can result in errors 18 - Abstract Classes, Polymorphism, and Inheritance 41

If you didn't have polymorphism You could have one shape class –That had a field to say what type the object actually was oval, rectangle, line –Then the draw method could use conditional statements to draw the right shape Based on the field –Adding new types Means modifying existing code –The code becomes harder to read and extend 18 - Abstract Classes, Polymorphism, and Inheritance 42

Interfaces If class A has a field of type class B and wants to call the notify method we need to know it is of type B –And if we change to class C we need to change class A But, if we use an interface we can add new classes that implement the same interface –Without changing class A 18 - Abstract Classes, Polymorphism, and Inheritance 43

Examples of Interfaces Many computers have USB ports –You can plug in any device that uses the USB interface Mouse, camera, external disk Electrical plugs in the US have one type of interface –You can plug in any device 18 - Abstract Classes, Polymorphism, and Inheritance 44

Interface use in ShapeExample ShapeInterface is an Interface ButtonPanel has an object of type ShapeInterface –Calls setShape and clearShapes on it ShapeComponent implements the interface 18 - Abstract Classes, Polymorphism, and Inheritance 45

Comparable Interface In chapter 16 the Searcher class had a linearFind method –that took an array of Comparable objects The Comparable interface allows you to write search methods –that don't depend on the class of the objects –just on the Comparable interface The Comparable interface –Defines the compareTo method 18 - Abstract Classes, Polymorphism, and Inheritance 46

List Interface What can you do with a list? –Add objects to it –Remove objects from it –Check to see if an object is in the list –Get an item at a specific position in the list Java defines a List interface –And several classes implement that interface ArrayList, Vector, LinkedList 18 - Abstract Classes, Polymorphism, and Inheritance 47

List Interfaces and Classes The List interface defines the basic methods for all lists The AbstractList class implements the List interface and provides some methods The ArrayList, Vector, and LinkedList classes inherit from AbstractList 18 - Abstract Classes, Polymorphism, and Inheritance 48

List Classes ArrayList –Uses an array to implement a list Grows and shrinks as needed to hold the data –Isn't thread safe Vector –Uses an array to implement a list –Is thread safe LinkedList –A list of nodes where each node has a link to the next one 18 - Abstract Classes, Polymorphism, and Inheritance 49

Thread safe Means that the data is protected so that two processes can't modify the data at the same time Computation can be broken into multiple processes –Like having more than one person help with cooking a meal –You need to be careful to not do the same step Like adding the salt 18 - Abstract Classes, Polymorphism, and Inheritance 50

18 - Abstract Classes, Polymorphism, and Inheritance 51 Summary In analysis you try to understand the problem you are trying to solve –What are the objects that are involved? What data and behavior do the objects need? In design you describe classes and their relationships –In a UML class diagram Inheritance is used to –Pull out common things into a parent class - Generalization –Allow a child to differ from a parent - Specialization Abstract classes are used to allow for easy addition of new subclasses –With some abstract method overriden by the child class Polymorphism allows for the right method to be executed based on the run-time type of the object