Abstract Classes 9-6-2013 - Clarkson University › ~jsearlem › cs242 › fa13 › ...public...
Transcript of Abstract Classes 9-6-2013 - Clarkson University › ~jsearlem › cs242 › fa13 › ...public...
Abstract Classes
9-6-2013
Abstract Classes
Introduction to Exception Handling
HW#2 posted; due 9/23/2013
Reading assignment: (on next slide)
HFJ2
Chapter 6: Using the Java API, pp. 154-160
Chapter 11: Exceptions (exercise: write the BeatBox code)
Effective Java 2
Chapter 7, Item 38: Check parameters for validity (pp. 181-183)
Chapter 7, Item 44: Write doc comments for all exposed API elements (pp. 203-208)
Chapter 8, Items 45, 46, 47 and 48 (pp. 209-220)
Chapter 9, Items 57, 58, 59, 60
Java Tutorial: Essential Java Classes trail: exceptions
Circle
FilledCircle
Point HAS-A
IS-A
(composition)
(inheritance)
1
Object
IS-A IS-A
<<interface>>
Comparable
implements implements
java.util.Arrays contains methods for manipulating arrays, such as searching & sorting
For example, there are overloaded sorting methods:
public static void sort( Object[] a )
is a modified merge sort which needs to compare object a1 with object a2, so elements must implement the Comparable interface
public static void sort( int[] a )
is a Dual-Pivot Quicksort, which yields O(n log(n)) performance on many data sets that cause other quicksorts to degrade to quadratic performance.
Note: This is a good example of polymorphism at work
problem: would like to sort the array of circles, but…
how to compare two circles?
java.util.Arrays has overloaded sorting methods: public static void sort( Object[] a )
is a modified merge sort which needs to compare object a1 with object a2, so…
elements must implement Comparable interface
import java.util.*;
Circle[] hoops = {
new Circle(1.0f, 1, 1),
new Circle(2.0f, 2, 2),
new Circle(3.0f, 3, 3)
};
Arrays.sort(hoops);
/* note:
Circle must implement Comparable
mergesort is used to sort objects
*/
public static void main(String[] args) { … }
class Math contains:
public static double random()
public static int abs(int a)
class Arrays contains:
public static int binarySearch(int[] a, int key)
A static method can be invoked without creating an object. Precede the method with the class name (not an object), e.g.
System.out.println( Math.random() );
System.out.println( Math.abs(n) );
Arrays.binarySearch( phoneNums, 2377);
cf. HFJ2, static methods, static variables, static constants pp. 274-284
Some classes exist only so their methods can be inherited (guarantees that all descendants share a common set of operations on their public interface)
cannot instantiate an abstract class!!
examples:
Number
Integer, Float, BigDecimal, …
Shape
Circle, Line, Rectangle, …
Integer
BigDecimal
Float
<<abstract>>
Number
isa
Byte
methods: byteValue(), intValue(), floatValue() …
Circle Rectangle Line
<<abstract>>
Shape
isa
Arrow
methods: draw(), boundingBox(), etc.
public abstract class Shape
{
// can define constants
public static final double TWO_PI = 2*Math.PI;
// can declare abstract methods
public abstract double computeArea();
public abstract void draw();
// can implement methods
public String geometry() { return “euclidean”; }
}
public class Circle
extends Shape
implements Comparable, Cloneable
{
// override draw() & computeArea()
// add code for compareTo()
}
public class Rectangle
extends Shape
implements Comparable, Cloneable
{
// override draw() & computeArea()
// add code for compareTo()
}
“template for a collection of related subclasses”
may contain instance variables, constants, concretely implemented methods
when a class extends an abstract class, it may implement all or some of the methods; if it does not implement all abstract methods, then it must be declared to be abstract itself
cannot instantiate an abstract class
can (and should) declare a reference to one
An interface is simply a list of unimplemented, and therefore abstract, methods. So how does an interface differ from an abstract class? The differences are significant.
An interface cannot implement any methods (no code allowed), whereas an abstract class can.
A class can implement many interfaces but can have only one superclass.
An interface is not part of the class hierarchy. Unrelated classes can implement the same interface.
Use an abstract class when you want a template for a collection of subclasses
Subclass when you want to extend a class and add some functionality, whether or not the parent class is abstract
Subclass when you must (e.g. Applets)
Define an interface when there is no common parent class with the desired functionality, and when you want only certain unrelated classes to have that functionality
Use interfaces as “markers” to indicate something about a class (e.g. Cloneable – can make a copy)
A common design pattern is to use both an interface and an abstract class
Circle
FilledCircle
Object
<<abstract>>
Shape
<<interface>>
Comparable
Point
IS-A
IS-A
IS-A
implements
implements
IS-A
Suppose that you would like an array containing a variety of circles, rectangles, lines, etc. How can you do this?
Circle[ ] drawing; // only can contain circles
Rectangle[ ] drawing; // still a problem
But with the abstract class Shape, can have
Shape[ ] drawing;
Shape thing = new Shape();
Shape thing = new Circle(100,200);
Shape thing = new Rectangle(50,25,75,40);
Shape[ ] drawing = new Shape[5];
Shape[0] = new Rectangle(50,25,75,40);
Circle c1 = new Circle(100,200); Shape[1] = c1;
// syntax error
// OK
// cannot instantiate an abstract class
// every Circle “is a” Shape (substitutability)
// OK
// creates an array of references, not of objects
// every Rectangle “is a” Shape (substitutability)
// OK
// OK
// every Rectangle “is a” Shape (substitutability) // OK
Element Function
public (Optional) Class is publicly accessible
abstract (Optional) Class cannot be instantiated
final (Optional) Class cannot be subclassed
class Name of the class
extends Super (Optional) Superclass of the class
implements
Interfaces
(Optional) Interfaces implemented by
the class
{ ClassBody } Provides the class's functionality
Note: we will learn about anonymous classes & static member classes later;
cf. EJ2, Item 22, p. 106
public final class Manager
{ … }
public final class String { … }
public final class System { … }
“final” class means that an applications programmer cannot create a subclass
User input errors
Device errors
Physical limitations
Code errors
program expects an int but user types Sept, user types a nonsyntactic URL, …
printer jams, server down, …
out of memory, exceeds disk space quota, …
invalid array index, attempt to pop an empty stack, attempt to dereference null, …
import java.io.*;
public class TestIO {
public static void main(String[] args) {
System.out.print("Enter your account:");
String buffer = readLine();
}
} can things go wrong?
In Java, the class designer MUST design for potential errors. Some errors can be handled within the class, but some must be handled in the application.
From a user’s point of view, the program should:
return to a “safe” state and allow the user to continue
or
allow the user to save work and then gracefully terminate
old approach: return a special error code that the calling method must check (e.g. return -1 to indicate that a file was not found; return null if an object was malformed; …).
this often causes problems and errors
exception handling: transfer control from where the error occurred to an error handler that can deal with the situation
this is a better solution