unit 9 1 unit 9: enhanced class design h in this unit: abstract classes packages basic programming...
Post on 21-Dec-2015
218 views
TRANSCRIPT
1unit 9
Unit 9: Enhanced class designUnit 9: Enhanced class design
In this unit:• Abstract classes
• Packages
basic programming
concepts
object oriented programming
topics in computer science
syllabus
2unit 9
Abstract ClassesAbstract Classes
An abstract class is a placeholder in a class hierarchy that represents a generic concept
An abstract class cannot be instantiated
We use the modifier abstract on the class header to declare a class as abstract
An abstract class often contains abstract methods (like an interface does), though it doesn’t have to
3unit 9
Abstract ClassesAbstract Classes
The child of an abstract class must override the abstract methods of the parent, or it too will be considered abstract
An abstract method cannot be defined as final (because it must be overridden) or static (because it has no definition yet)
The use of abstract classes is a design decision; it helps us establish common elements in a class that is too general to instantiate
4unit 9
Abstract classes: exampleAbstract classes: example
Paint Brush
Paint Brush application
5unit 9
Paint-brush applicationPaint-brush application
• We want to represent the drawing as a collection of objects, each represents a certain shape
• We want to represent each shape with a suitable class; objects of these classes will know how to draw themselves
• The classes have common properties (location, size, color, ...) and common behaviors (moveTo(), resize(), ...)
• We want to have a common superclass for all these classes which will define all the common properties and behaviors
6unit 9
Common superclass Shape Common superclass Shape
Shape
Rectangle Ellipse
moveTo(x,y)
moveBy(dx,dy)
resize(factor)
setLineColor(color)...
draw()
contains(x,y)draw()
contains(x,y)
7unit 9
Class shape is AbstractClass shape is Abstract
Class shapeshape was defined to ease our design and maintenance by putting all the common properties of the different shapes in one place
However, we will never want to create instances of class shape, only of its subclasses
We thus define the class shape as an abstract class; now we cannot create instances of class shape, only instances of subclasses of shape which are not defined abstract
8unit 9
Class Shape: definitionClass Shape: definition
// A geometrical shape. A shape has a location and size,// and it can draw itself on the screen ...public abstract class ShapeShape {
// The top-left corner of the rectangular area that // contains the shape protected int x,y;
// The dimension of the shape (of the rectangular // area that contains the shape) protected int width, height;
// The color of the border of the shape private Color lineColor;
// ... other properties
9unit 9
Class Shape: methodsClass Shape: methods // Construct new shape with given location & dimension public Shape(int x, int y, int width, int height) { this.x = x; this.y = y; this.width = width; this.height = height; } // Return the color of the border of this shape public Color getLineColor() { return lineColor; } public void moveTo(int x, int y) {// Move to new location this.x = x; this.y = y; } public void moveBy(int dx, int dy) {//Move by given offset moveTo(x+dx, y+dy); }
10unit 9
Why abstract methods Why abstract methods
Problem: in the design diagram, the draw() method appears in the interface of all subclasses of class shape, but is implemented differently in each one of them
Solution: we define an abstract method in class shape to require that every shape can draw itself; we then override this method in every specific subclass
Polymorphism: we can draw an heterogeneous collection of shapes with a single loop
11unit 9
Abstract methods of class ShapeAbstract methods of class Shape
// A geometrical shape. ...
public abstract class ShapeShape {
... state variables as before
// Draws this shape public abstract void draw();
// Checks a given point is in the // interior of this shape public abstract boolean contains(int x, int y);
12unit 9
Using abstract classesUsing abstract classes// A picture made of geometrical shapespublic class PaintBrushPicturePaintBrushPicture { private Vector shapes; // Construct an empty picture public PaintBrushPicture() { shapes = new Vector(); } // Add a new shape to the picture public void add(shape shape) { shapes.addElement(shape); } // Paint this picture public void draw() { for (int i=0; i<shapes.size(); i++) { ((Shape)shapes.elementAt(i)).draw(); } }
13unit 9
Abstract classes hierarchyAbstract classes hierarchy
Now, a subclass of class shape must either be abstract or implement all the abstract classes that are defined in class shape
14unit 9
Subclass RectangleSubclass Rectangle// A shape of a rectangle in the planepublic class RectangleRectangle extends shape { // Constructs new Rectangle with location & dimensions public Rectangle(int x, int y, int width, int height){ super(x, y, width, height); } // Draws this rectangle public void draw() { Brush painter = new Brush(); painter.setLocation(x,y); painter.moveForwards(width); painter.turnRight(90); painter.moveForwards(height); painter.turnRight(90); painter.moveForwards(width); painter.turnRight(90); painter.moveForwards(height);
}
15unit 9
Chess exampleChess example
ChessPiece
Pawn Rook
moveTo(x,y)
moveBy(dx,dy)
getLocation()
getPossibleMoves()...
getPossibleMoves()getPossibleMoves()getPossibleMoves()
Knight . . .
16unit 9
Logic circuits exampleLogic circuits example
ElectronicGate
AndGate OrGate
getNumberOfInputs()
getInputVoltage(i)
setInputVoltage(i)
getOutputVoltage()
process()
process()process() process()
NotGate . . .
17unit 9
More complex structures: interfaceMore complex structures: interface
Paint Brush
Paint Brush application
Suppose we want to paint also pixels and lines:
18unit 9
No common superclass existsNo common superclass exists
Object
shape Line Point
Rectangle Ellipse Polygon
RoundRectangle We don’t have a common viewpoint of these classes that sees the method draw
Pixel
19unit 9
Solution: interfaceSolution: interface
Object
shape Line Point
Rectangle Ellipse Polygon
RoundRectangle
Drawable
Pixel
20unit 9
Interface DrawableInterface Drawable
// An interface for classes whose instances know how to// draw themselves on a graphical window
public interface DrawableDrawable {
// Draw this object. public void draw();}
// Represents a pixel on a graphical areapublic class PixelPixel extends Point implements Drawable { ...
// Draw this pixel on the screen public void draw() { ... } ...
21unit 9
Abstract classes & interfacesAbstract classes & interfaces
// A geometrical shape. A shape has a location and// size it can draw itself on the screen ...
public abstract class shapeshape implements Drawable {
// The top-left corner of the rectangular area // that contains the shape protected int x,y;
...
we do not have to declare again the abstract method draw()
22unit 9
PaintBrushPicturePaintBrushPicture example example
// A picture made of geometrical shapes
public class PaintBrushPicturePaintBrushPicture {
// The elements (shapes) that compose this picture private Vector elements;
...
// Draw this picture public void draw() { for (int i=0; i< elements.size(); i++) { ((Drawable)elements[i]).draw(); } }
23unit 9
VisualizationVisualization
RoundRectagle
getLocation()
moveTo()
moveBy()
draw()
toString()
...
getArcSize()
setArcSize()
Object view
shape view
RoundRectangle
Drawable view
24unit 9
Interface MoveableInterface Moveable
// An interface for classes whose instances can move
public interface MoveableMoveable {
// Moves this object to a new location public void moveTo(int x, int y);
// Moves this object by a given offset public void moveBy(int dx, int dy);
}
25unit 9
Abstract classes and multiple interfacesAbstract classes and multiple interfaces
// A geometrical shape: a shape has a location and// size it can draw itself on the screen, and move
public abstract class shape implements Drawable, Moveable{
...
// Moves this shape to a new location public void moveTo(int x, int y) { this.x = x; this.y = y; }
...
26unit 9
Unit 9: Enhanced class designUnit 9: Enhanced class design
• Abstract classes
• Packages
27unit 9
PackagesPackages
Java lets us group our classes into packages When we define classes we often define them as
part of a package of related classes To group several classes into a package we must:
1. Specify in each of the source files of the class that the class belongs to the package
2. Put all class files under a directory with the name of the package; the directory that contains this directory should be in our CLASSPATH
28unit 9
PackagesPackages
package shapes;
// A geometrical shape. A shape has a location and // sizepublic abstract class shapeshape {
// The top-left corner of the rectangular area
// that contains the shape protected int x,y;
...
29unit 9
PackagesPackages
package shapes;
// A shape of a rectangle ...
public class RectangleRectangle extends shape {
// Constructs a new Rectangle with given // location and dimenstions public Rectangle(int x, int y, int width, int height){ super(x, y, width, height); }
...
30unit 9
PackagesPackages
package paintbrush;
import shapes.*;import java.util.Vector;import java.awt.*;
// A canvas on which you can draw geometrical shapespublic class PaintBrushCanvasPaintBrushCanvas extends Canvas { private PaintBrushPicture picture;
// Construct a new PaintBrushCanvas public PaintBrushCanvas() { picture = new PaintBrushPicture(); }
31unit 9
PackagesPackages
shapes
shape.class
Rectangle.class
Ellipse.class
Polygon.class
paintbrush
PaintBrushCanvas.class
PaintBrushPicture.class
PaintBrush.class
my_classes
(c:)
32unit 9
Reusability: the Java LibraryReusability: the Java Library
Java supplies hundreds of predefined classes, for representing commonly used object types. In addition the programmer can define his/her own new classes
The Java API (Application Programmer Interface) is the library of classes supplied by Java
The classes in the Java API are separated into packages
Each package contains a set of classes that are related in some way
33unit 9
The Java PackagesThe Java Packages
java.applet
java.awt
java.beans
java.io
java.lang
java.math
...
java.net
java.rmi
java.security
java.sql
java.text
java.util
34unit 9
Importing PackagesImporting Packages
Using a class from a Java package can be accomplished by using its fully qualified name:
java.util.Random random =
new java.util.Random(); Instead, the class can be imported once with the
import statement: import java.util.Random;
. . .
Random random = new Random();
35unit 9
Importing PackagesImporting Packages
You can also import all the classes in a given package with a single import statement:
import java.util.*;
The java.lang package is automatically imported into every Java program.