Abstract Classes 9-6-2013 - Clarkson University › ~jsearlem › cs242 › fa13 › ...public...

26
Abstract Classes 9-6-2013

Transcript of Abstract Classes 9-6-2013 - Clarkson University › ~jsearlem › cs242 › fa13 › ...public...

Page 1: Abstract Classes 9-6-2013 - Clarkson University › ~jsearlem › cs242 › fa13 › ...public static void sort( Object[] a ) is a modified merge sort which needs to compare object

Abstract Classes

9-6-2013

Page 2: Abstract Classes 9-6-2013 - Clarkson University › ~jsearlem › cs242 › fa13 › ...public static void sort( Object[] a ) is a modified merge sort which needs to compare object

Abstract Classes

Introduction to Exception Handling

HW#2 posted; due 9/23/2013

Reading assignment: (on next slide)

Page 3: Abstract Classes 9-6-2013 - Clarkson University › ~jsearlem › cs242 › fa13 › ...public static void sort( Object[] a ) is a modified merge sort which needs to compare object

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

Page 4: Abstract Classes 9-6-2013 - Clarkson University › ~jsearlem › cs242 › fa13 › ...public static void sort( Object[] a ) is a modified merge sort which needs to compare object

Circle

FilledCircle

Point HAS-A

IS-A

(composition)

(inheritance)

1

Object

IS-A IS-A

<<interface>>

Comparable

implements implements

Page 5: Abstract Classes 9-6-2013 - Clarkson University › ~jsearlem › cs242 › fa13 › ...public static void sort( Object[] a ) is a modified merge sort which needs to compare object

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

Page 6: Abstract Classes 9-6-2013 - Clarkson University › ~jsearlem › cs242 › fa13 › ...public static void sort( Object[] a ) is a modified merge sort which needs to compare object

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

Page 7: Abstract Classes 9-6-2013 - Clarkson University › ~jsearlem › cs242 › fa13 › ...public static void sort( Object[] a ) is a modified merge sort which needs to compare object

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

*/

Page 8: Abstract Classes 9-6-2013 - Clarkson University › ~jsearlem › cs242 › fa13 › ...public static void sort( Object[] a ) is a modified merge sort which needs to compare object

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

Page 9: Abstract Classes 9-6-2013 - Clarkson University › ~jsearlem › cs242 › fa13 › ...public static void sort( Object[] a ) is a modified merge sort which needs to compare object

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, …

Page 10: Abstract Classes 9-6-2013 - Clarkson University › ~jsearlem › cs242 › fa13 › ...public static void sort( Object[] a ) is a modified merge sort which needs to compare object

Integer

BigDecimal

Float

<<abstract>>

Number

isa

Byte

methods: byteValue(), intValue(), floatValue() …

Page 11: Abstract Classes 9-6-2013 - Clarkson University › ~jsearlem › cs242 › fa13 › ...public static void sort( Object[] a ) is a modified merge sort which needs to compare object

Circle Rectangle Line

<<abstract>>

Shape

isa

Arrow

methods: draw(), boundingBox(), etc.

Page 12: Abstract Classes 9-6-2013 - Clarkson University › ~jsearlem › cs242 › fa13 › ...public static void sort( Object[] a ) is a modified merge sort which needs to compare object

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”; }

}

Page 13: Abstract Classes 9-6-2013 - Clarkson University › ~jsearlem › cs242 › fa13 › ...public static void sort( Object[] a ) is a modified merge sort which needs to compare object

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()

}

Page 14: Abstract Classes 9-6-2013 - Clarkson University › ~jsearlem › cs242 › fa13 › ...public static void sort( Object[] a ) is a modified merge sort which needs to compare object

“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

Page 15: Abstract Classes 9-6-2013 - Clarkson University › ~jsearlem › cs242 › fa13 › ...public static void sort( Object[] a ) is a modified merge sort which needs to compare object

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.

Page 16: Abstract Classes 9-6-2013 - Clarkson University › ~jsearlem › cs242 › fa13 › ...public static void sort( Object[] a ) is a modified merge sort which needs to compare object

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)

Page 17: Abstract Classes 9-6-2013 - Clarkson University › ~jsearlem › cs242 › fa13 › ...public static void sort( Object[] a ) is a modified merge sort which needs to compare object

A common design pattern is to use both an interface and an abstract class

Page 18: Abstract Classes 9-6-2013 - Clarkson University › ~jsearlem › cs242 › fa13 › ...public static void sort( Object[] a ) is a modified merge sort which needs to compare object

Circle

FilledCircle

Object

<<abstract>>

Shape

<<interface>>

Comparable

Point

IS-A

IS-A

IS-A

implements

implements

IS-A

Page 19: Abstract Classes 9-6-2013 - Clarkson University › ~jsearlem › cs242 › fa13 › ...public static void sort( Object[] a ) is a modified merge sort which needs to compare object

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;

Page 20: Abstract Classes 9-6-2013 - Clarkson University › ~jsearlem › cs242 › fa13 › ...public static void sort( Object[] a ) is a modified merge sort which needs to compare object

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

Page 21: Abstract Classes 9-6-2013 - Clarkson University › ~jsearlem › cs242 › fa13 › ...public static void sort( Object[] a ) is a modified merge sort which needs to compare object

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

Page 22: Abstract Classes 9-6-2013 - Clarkson University › ~jsearlem › cs242 › fa13 › ...public static void sort( Object[] a ) is a modified merge sort which needs to compare object

public final class Manager

{ … }

public final class String { … }

public final class System { … }

“final” class means that an applications programmer cannot create a subclass

Page 23: Abstract Classes 9-6-2013 - Clarkson University › ~jsearlem › cs242 › fa13 › ...public static void sort( Object[] a ) is a modified merge sort which needs to compare object

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, …

Page 24: Abstract Classes 9-6-2013 - Clarkson University › ~jsearlem › cs242 › fa13 › ...public static void sort( Object[] a ) is a modified merge sort which needs to compare object

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.

Page 25: Abstract Classes 9-6-2013 - Clarkson University › ~jsearlem › cs242 › fa13 › ...public static void sort( Object[] a ) is a modified merge sort which needs to compare object

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

Page 26: Abstract Classes 9-6-2013 - Clarkson University › ~jsearlem › cs242 › fa13 › ...public static void sort( Object[] a ) is a modified merge sort which needs to compare object

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