Title: CS242 Advanced Programming Concepts in Java
1CS242Advanced Programming Concepts in Java
- 9/11/07
- class design
- interfaces abstract classes
Prof. Searleman jets_at_clarkson.edu
2Announcements
- Clarkson Student Chapter of the ACM
- organizational meeting on Thursday, 9/13, at 700
pm in the CEC (Snell 130) - COSI/ITL meeting
- tomorrow night, 700 pm, ITL
- Greg Lotko (Clarkson grad) from IBM
- will talk about careers on Thursday, 9/13 at
1000 am in the ITL - Johnson Johnson peer info session
- Thursday, September 13, at 730 p.m. in Snell
214
a horrible death to die
3Outline
- Interfaces
- Comparable
- compareTo()
- Abstract class
- Immutable objects
- Exception handling
- HW2 due Tuesday, 9/18/07
- Read OODP, Ch. 7pp.261-280 Effective Java, Ch.
3pp 25-44 - Java Tutorial
4implements
implements
implements
5Comparable interface
- public interface Comparable
- public int compareTo( Object o )
-
- for x, y objects of the same class
- x.compareTo(y) lt 0 means x lt y
- x.compareTo(y) gt 0 means x gt y
- otherwise, x is neither lt nor gt y
- recommended that compareTo() is consistent with
equals() - if o cannot be cast to the same class as x, then
generates a ClassCast Exception
6- public class Student
- private String name
- public int compareTo( Object o )
-
- Student other (Student) o
- if (this.name lt other.name)
- return -1
- if (this.name gt other.name)
- return 1
- return 0
-
severely flawed
This doesnt implement the Comparable
interface String is an object cannot use lt or
gt to compare
7- public class Student implements Comparable
- private String name
- public int compareTo( Object o )
-
- Student other (Student) o
- return ((this.name).compareTo(other.name))
-
use lt gt to compare primitives invoke
compareTo() method to compare objects remember
to have implements Comparable on the class
header
8Contract for compareTo()
- sgn(x.compareTo(y)) -sgn(y.compareTo(x))
- x.compareTo(y) gt 0 y.compareTo(z) gt 0 implies
x.compareTo(z) gt 0 - x.compareTo(y) 0 implies that for all z,
sgn(x.compareTo(z)) sgn(y.compareTo(z)) - strongly recommended that
- (x.compareTo(y) 0) (x.equals(y))
- i.e. consistent with equals
9Methods common to all classes
- Item 7 equals()
- - override Object.equals() for value classes
- Item 8 hashCode()
- - always override Object.hashCode() when you
override equals() - Item 9 always override toString()
- Item 11 consider implementing Comparable
- Note
- - equals(), hashCode() toString() are methods
in class Object - - compareTo() is not a method in class Object
it is a method in the Comparable interface
10Generic form for equals()
- public class X
- // assume fields f1 (float), f2 (object), , fk
- public boolean equals(Object o)
- if (o null) return false
- if (o this) return true
- if (!(o instanceof X))
- return false
- X other (X) o
- return ( (this.f1 other.f1)
- ( (this.f2).equals(other.f2)
-
) - // use for primitive fields, equals() for
objects
11Generic form for hashCode()
- public class X
- // assume fields f1 (float), f2 (object), , fk
- public int hashCode()
- int result 17
- result 37result Float.floatToIntBits(f1)
- result 37result f2.hashCode()
-
- result 37result // cf. pp 38-39
- return result
-
12- public class X implements Comparable
- public int compareTo( Object o )
- // assume fields f1 (float), f2 (object), , fk
- X other (X) o
- if ((this.f2).compareTo(other.f2) lt 0)
- return -1
- if ((this.f2).compareTo(other.f2) gt 0)
- return 1
- return 0
- // use lt,gt to compare primitive fields,
- // use compareTo() for object fields
13Abstract Class
- 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,
14methods byteValue(), intValue(),
ltltabstractgtgt Number
isa
15methods draw(), computeArea()
ltltabstractgtgt Shape
isa
16- public abstract class Shape
-
- // can define constants
- public static final double TWO_PI 2Math.PI
- // can declare abstract methods
- public abstract double computeArea()
- public abstract void draw()
- // can implement methods
- public String aka() return euclidean
17- 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()
18Abstract class
- 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 declare a reference to one
19Interface
- specification of an interface or protocol for a
class (may be implemented in unrelated classes) - may not contain instance variables or any code,
but may contain (static final) constants - when a class states that it implements an
interface, it MUST implement ALL methods in the
interface - a class can implement more than one interface
- all methods in an interface are abstract and
public, with or without the modifiers public
and/or abstract - an interface can be empty, in which case it is a
marker for a special property (e.g. Cloneable,
Serializable) - an interface can be used to implement callbacks
- interfaces can extend other interfaces
- cannot instantiate an interface
- can declare a reference to one
20Interface vs. Abstract Class
- 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,
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.
21- 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)
22- A common design pattern is to use both an
interface and an abstract class
23methods toString(), equals(), getClass(),
methods abstract computeArea(), abstract draw(),
aka()
methods constructors, get/setCenter(),
get/setRadius(), computeArea(), toString(),
equals(), compareTo()
methods constructors, get/setColor(),
toString(), equals()
24Class Declaration Elements
25Preventing inheritance
- public final class Manager
-
- public final class String
-
26Item 13 Favor immutability
- cf. Effective Java, p. 63
- key idea if an object is immutable, then other
classes using the object have no way to change
the data in the object - examples
- String
- BigInteger
- PhoneNumber
- Point (java.awt.Point is not immutable, but
should be)
275 Rules for Immutability
- 1. No mutator methods
- 2. No methods can be overridden
- 3. Make all fields (instance variables) final
- 4. Make all fields private.
- 5. Ensure exclusive access to any mutable
components
28- // Example immutable points
- public final class Point
-
- private final int x
- private final int y
-
- public Point(int x, int y)
-
- this.x x this.y y
-
29- public int getX()
- return x
- public int getY()
- return y
-
- public boolean equals(Object o)
- public int hashCode()
- public String toString()
- // end class Point
equals(), hashCode(), toString() as recommended
30Immutable or not?
- if the object is supposed to be a constant, it
should be immutable - if the object will be changed frequently, it
should be mutable - if the object is very large, be careful if you
opt for immutability (copying the object will be
slow) - sets and other collections returned from a
method should be immutable to preserve
encapsulation
31Exception Handling
- exceptions as objects
- checked vs. unchecked exceptions
- throwing exceptions (propagation)
- handling exceptions (try/catch)
32What to do when an error is detected?
- From a users 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
33Sources of error
- 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,
34Exception Handling
- transfer control from where the error occurred to
an error handler that can deal with the situation - traditional 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 is a
PROBLEM
35- import java.io.
- public class TestIO
- public static void main(String args)
- System.out.print("Enter your account")
- String buffer readLine()
-
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.
36Java Exceptions
- Java allows every method an alternative exit path
if it is unable to complete its task in the
normal way. - In this situation, the method does NOT return a
value instead it creates throws an exception
object that encapsulates the error information
and it exits immediately - Javas exception handling system will search the
call stack for an exception handler that can
deal with this error
37- public class Magic
- public String castSpell(int n)
- // end castSpell
- public class Lamp
- public void init()
- Magic m new Magic()
- String arg m.castSpell(42)
-
- // end Lamp
- public class Test
- public static void main()
- Lamp t new Lamp()
- t.init()
-
- // end Test
3. Magic.castSpell() currently executing
38- call stack
- main() Lamp.init() Magic.castSpell()
- case 1 normal operation. castSpell() returns a
string to the point of call - case 2 exception occurs. execution of
castSpell() immediately terminates, a string is
not returned, do not return to point of call
search backwards through call stack until an
appropriate exception handler is found if none
found, program terminates
39Types of Exceptions
- checked (meaning the compiler can check)
- - most application exceptions are checked
- - if you call a method which throws a checked
exception, you MUST specify to the compiler how
this will be handled - either (1) propagate (or throw) it, or
- (2) handle the error at once
(try/catch) - unchecked - subclasses of java.lang.RuntimeExcepti
on or java.lang.Error - - programming errors or system errors
40Catching Exceptions
- try
-
- // do stuff
- // more stuff
-
- catch(IOException ioe)
-
- // handle this case
-
- catch(Exception e)
-
- // catch-all
41- // Alternative 1 propagate the error
- // (let someone else in the call stack handle it)
- public static String readLine() throws
IOException -
- // in the body of this method, either
- // (1) there is a call to another method which
throws an exception (e.g. System.in.read) - // or (2) this method itself creates and throws
an exception throw new ltexceptiontypegt
42- // Somewhere in the calling stack, there must be
a // try/catch to handle the exception that was
thrown - public static String readLine() throws
IOException -
- public static void main(String args)
- System.out.print("Enter a line")
- try
- System.out.println(readLine())
- catch(IOException e)
- System.out.println(e.getMessage())
-
43- // Alternative 2 handle the error internally
- public static String readLine()
- try
- // in the body of this method, something
- // potentially throws an exception
- catch(IOException e)
- // do something sensible about it
-
44- // Exception is handled by the method nothing
- // needs to be done within the calling stack
- public static String readLine()
-
- public static void main(String args)
- System.out.print("Enter a line")
- System.out.println(readLine())
-
45Handling exceptions
- try
- // stuff
- catch (SomeException e1 )
- // do something sensible about
- // the error
What to do?
- if caused by user error, give the user a chance
to correct it
- take a sensible default action
- print (or display) an error message where?
- display pop-up dialog, etc.
46What to do when an exception occurs?
- All exceptions inherit the properties methods
of Throwable - useful methods include
- String getMessage() // error message
- String toString() // short description
- void printStackTrace() // backtrace
- void printStackTrace(PrintStream)
- tip print to standard error stream
- System.err.println(system malfunction)
47Handling exceptions
- try
- // stuff
- catch (SomeException e1 )
-
System.err.println( e1.getMessage() )
System.err.println( e1.getClass().getName())
e1.printStackTrace( System.err )