AbstractClassesInterfacesPolymorphism

Download Report

Transcript AbstractClassesInterfacesPolymorphism

Abstract Classes, Interfaces,
Polymorphism
Barb Ericson
Georgia Tech
[email protected]
April 2010
AbstractClassesInterfacesPolymorphism
1
Learning Goals
• Understand at a conceptual and practical
level
– Inheritance
– Abstract Classes
– Interfaces
– Polymorphism
Advanced-OO
2
Object-Oriented Principles
• Objects with data (fields) and operations
(methods)
– Usually classes too
• Inheritance
– Hierarchy of types
– Generalization / Specialization
• Polymorphism
– Executing the right method based on the type
of the object at run-time
Advanced-OO
3
Abstract Classes
• Abstract classes are classes that can’t be
instantiated. Abstract classes can only be
Food
subclassed.
price
calories
Hamburger
Coke
• Create an abstract class by using the
keyword abstract in the class declaration.
– public abstract class Food
Advanced-OO
4
Why use an Abstract Class?
• Represents an abstract idea (like a Shape or a
List)
• Holds methods common to several related
classes
• Holds attributes common to several related
classes
• Enforce naming convention by abstract methods
that must be overridden by children
• Allows for general algorithms based on abstract
methods with customization by children
Advanced-OO
5
Interfaces
• Interfaces are a description of behavior.
– They are a special kind of abstract class that
only has public abstract methods and
constants.
public interface ShapeInterface
{
public void setShape(int shape);
}
– You don’t have to declare the methods as
abstract or public
• They automatically are
Advanced-OO
6
Classes Implement Interfaces
• Classes that implement interfaces must
provide the implementations for the
methods specified in the interface.
– Or be declared abstract as well
public class ShapeCanvas implements
ShapeInterface
{
public void setShape(int shape)
{ code to handle set shape }
}
Advanced-OO
7
Why use an Interface?
• Separates what from who
– I don’t care who you are I just need a way to
talk to you
– Choose from several implementers
• A class can implement many interfaces
but inherit from only one class
– like multiple inheritance but easier to use
– thinner than inheritance
Advanced-OO
8
Interfaces Versus Inheritance
• When a class inherits from a parent class it
inherits all the object attributes and methods.
– With inheritance it inherits the structure and behavior
of the parent class.
– With an interface it inherits only the method names
and parameter lists.
• A class can inherit from only one parent class
– public class Person extends Object
• A class can implement more than one interface.
– public class ShapeCanvas implements
Interface1,Interface2,…
Advanced-OO
9
Comparable Interface
• How would you compare any two objects?
– And decide if one is less than, equal too, or
greater than the other
• It would depend on the Class of the
objects being compared
– For String objects compare the letters in the
string
• Implement the Comparable interface
– public int compareTo(Object object)
Advanced-OO
10
Comparable Exercise
• How would you compare two Person
objects?
– Implement the Comparable interface
public class Person implements
Comparable<Person>
– Add a compareTo method
public int compareTo(Person comparePerson)
• Compare the last names first
– If they are equal compare the first names
• The String class implements Comparable so you
can use the results of comparing the last name
and first name
Advanced-OO
11
Collections - java.util
• Used to hold objects
– Uses wrapper classes to hold primitive values
int numItems = 3;
Integer numItemsInt = new Integer(numItems);
• Three basic types
– List - ordered list of objects
• Can have duplicate objects
– Set - group of objects without an order
• No duplicate objects allowed
– Map - map of keys to objects
Advanced-OO
12
List and Set Interfaces and Classes
<<interface>>
Collection
<<interface>>
List
ArrayList
Vector
<<interface>>
Set
LinkedList
HashSet
<<interface>>
SortedSet
TreeSet
Advanced-OO
13
Collection Methods
• Add an object to a collection
boolean add(Object object); // optional
• Remove an object from a collection
boolean remove(Object object); //optional
• See if the collection has the object in it
boolean contains(Object object);
• Add all objects in another collection
boolean addAll(Collection collection); // optional
• Get the intersection of two collections
boolean retainAll(Collection collection); // optional
• Empty a collection
Void clear();
Advanced-OO
14
Use Interface Name as Type
• Declare the type of the collection variable to be
one of the main interface types
– List
– Set
• SortedSet
– Map
• SortedMap
• This allows you to change the implementation
without changing much code
Map addressMap = new HashMap();
Map addressMap = new Hashtable();
Advanced-OO
15
Polymorphism
• Literally: many forms
• In Object-Oriented
development it means
that what happens
when a message is
sent to an object
depends on the type
(class) of the object at
runtime
Advanced-OO
16
How Does Polymorphism Work?
• If a class is declared to be final
– then the compiler can figure out the location
of a method that matches the message
• If a class can be subclassed
– then a variable declared to be of the parent
type can point to an object of the parent class
or any subclass at run-time
– the compiler can’t determine the method to
invoke
– the method to invoke is figured out at run-time
Advanced-OO
17
Shape Panel Exercise
• Execute the main
method of
ShapePanel
• Click the Rectangle
button and then click
and drag to position
the rectangle
• Click the Oval button
and click and drag to
position the oval
Advanced-OO
18
Class Diagram for ShapePanel
ShapePanel
ShapeInterface
1
Shape
draw()
Oval
draw()
*
1
1
ShapeCanvas
1
1
ButtonPanel
paint()
Rectangle
draw()
Advanced-OO
19
Polymorphism - Many Forms
• Polymorphism is overloading that is resolved at
execution time, and is also called dynamic or run-time
binding.
• Say you have an array of Shapes that actually holds
objects that are subclasses of shape.
– When you ask a shape to draw itself what gets drawn depends
on the run-time type.
Shape
draw()
Oval
draw()
Rectangle
draw()
Advanced-OO
20
Add Abstract Class Subclass Exercise
– Create a new class Line which is a subclass
of Shape.
• Use Oval.java or Rectangle.java as starting points
– Add “Line” to the array of shapeNames in
ButtonPanel
– Compile and run ShapePanel to try it out.
Advanced-OO
21
Advantages to Polymorphism
• Used to create general algorithms that
work on objects of different types
– Collections that hold Objects
• List, Set, Stack, Queue, Map
• Makes it easy to add new types
– Just create the new class and implement the
required operations
– Don’t change existing code
Advanced-OO
22
Summary
• Class fields are on an object of the class Class
– Not on objects of the class
• Class methods can only work on class fields
– Not object fields
• Objects inherit fields and methods from a parent
class
– But need to use public methods to access private
inherited fields
• Polymorphism allows you to write general
methods based on a common parent or interface
Advanced-OO
23