Java Enterprise Technology: Java language 3 - PowerPoint PPT Presentation

1 / 62
About This Presentation
Title:

Java Enterprise Technology: Java language 3

Description:

e.g., String, PoliteSpeaker. Interfaces: ... returns a String giving information about ... e.g., comparing Strings, use .equals() equals(Object o) contract ... – PowerPoint PPT presentation

Number of Views:66
Avg rating:3.0/5.0
Slides: 63
Provided by: kurtste
Category:

less

Transcript and Presenter's Notes

Title: Java Enterprise Technology: Java language 3


1
Java Enterprise TechnologyJava language 3
  • CMPSC 332/609 Spring 2005
  • Kurt Steinkraus

2
Today
  • Error handling
  • Coding and naming conventions
  • Responsibilities of objects

3
Questions?
4
Error handling
  • Standard methods
  • exit(-1)
  • Global error flag
  • Status return code
  • Java (and C) add one more
  • Exceptions

5
Exception motivation
int readData() if(readFirstPart() -1)
return -1 if(readSecondPart() -1)
return -1 // ... return 0
if(openFile() -1) handleError() if(readData(
) -1) handleError() if(readMoreData()
-1) handleError() if(closeFile() -1)
handleError()
int readFirstPart() if(file.readBytes(...))
return -1 // ... return 0
6
Exception handling
  • An exception denotes an exceptional (unusual,
    error-like) situation
  • Exceptions allow for centralized error handling
  • Not passing/checking error code everywhere

7
Exception semantics
  • Try executing this code
  • If an error happens, throw an exception
  • If an error is thrown, catch the error and do
    something with it (possibly re-throw it)

8
Exception example
void readData() throws IOException
readFirstPart() readSecondPart() // ...
try openFile() readData()
readMoreData() closeFile()
catch(IOException e) handleError()
void readFirstPart() throws IOException
if(file.readBytes(...)) throw new
IOException() // ...
9
Notice throwing exceptions
  • void readFirstPart() throws IOException
  • if(file.readBytes(...))
  • throw new IOException()
  • // ...
  • If an error occurs, create a new instance of an
    exception, and throw it
  • You can give it some explanatory text
  • throw new IOException("can't read name!")

10
Catching exceptions
  • When an exception is thrown, it propagates up the
    call stack until it reaches a catch block that
    handles that exception type

11
Exception catching example
void readData() throws IOException
readFirstPart() readSecondPart() // ...
try openFile() readData()
readMoreData() closeFile()
catch(IOException e) handleError()
no
void readFirstPart() throws IOException
if(file.readBytes(...)) throw new
IOException() // ...
12
Notice try-catch
  • try
  • openFile()
  • readData()
  • readMoreData()
  • closeFile()
  • catch(IOException e)
  • handleError()

If an IOException isthrown anywhere in the try
block,
control flow goes tothe catch block,
and then continuesbelow
13
Notice declaring exceptions
  • void readData() throws IOException
  • readFirstPart()
  • // ...
  • You must declare that a method throws an
    exception if
  • It throws the exception directly
  • It does not catch that exception if thrown by a
    called method (like readFirstPart)

14
Two exception types
  • Checked exceptions must be declared or caught
  • Like IOException
  • Unchecked exceptions dont have to be declared or
    caught

15
Two exception types
  • Checked exceptions are problems you would want to
    handle in your program
  • Unchecked exceptions are problems you probably
    cant handle
  • Theyre unexpected
  • They denote bugs in your program
  • They denote catastrophic failure

16
Throwable class hierarchy
Throwable
Exception
Error
Unchecked errors
Checked errors
RuntimeException
Unchecked errors
17
Kinds of Throwable
  • Error subclasses unchecked
  • Hardware or java executable problems
  • Exception subclasses checked
  • Normal exceptional conditions, e.g., file not
    found, disk full
  • RuntimeException subclasses unchecked
  • Bugs in your program, e.g., divide by zero

18
Finding an exception to throw
  • There are a lot of existing exceptions in the
    java standard library
  • Standard ones
  • NullPointerException
  • IllegalArgumentException
  • IOException
  • You can create your own exceptions too

19
Creating custom exceptions
  • public class MyException
  • extends RuntimeException
  • public MyException() super()
  • public MyException(String str)
  • super(str)
  • // any extra fields or methods
  • // used to describe what went wrong

20
finally block
  • Sometimes you want some code to execute no matter
    what
  • Normal execution
  • Caught exception
  • Uncaught exception
  • Use a finally block

21
finally block example
  • openFile()
  • try
  • // do things to the opened file
  • // ...
  • finally
  • closeFile()

22
Exceptions pros and cons
  • Pro
  • Centralized error handling
  • Cleaner code
  • Con
  • Cant succinctly handle lots of checked
    exceptions
  • Cant succinctly ignore exceptions
  • Messier code

23
Questions on error handling?
24
Java coding conventions
  • Conventions used in standard library (and you can
    look at the source!)
  • http//java.sun.com/docs/codeconv/
  • Try to use Suns coding conventions
  • Come up with variations if you like, but have
    good reasons and be consistent

25
Naming conventions
  • Packages
  • If for wide distribution, use a unique prefix,
    preferably inverted Internet domain name
  • e.g., us.steinkraus.examples

26
Naming conventions
  • Classes
  • Mixed case, each word starts with capital
  • e.g., String, PoliteSpeaker
  • Interfaces
  • Samewe want to know that were talking about an
    object with a particular type, but it shouldnt
    matter if it is a class or interface

27
Naming conventions
  • Methods
  • Mixed case, lowercase first letter, second and
    following words start with capital
  • Active verb followed by noun
  • e.g., getValue(), processData()
  • Solitary noun means tiny accessor method
  • e.g., key(), intValue()

28
Naming conventions
  • Variables
  • Mixed case, lowercase first letter, second and
    following words start with capital
  • Noun
  • e.g., count, windowWidth
  • Single-letter names are OK for small-scope
    temporary variables

29
Naming conventions
  • Constants
  • All capitals, words separated by underscores
  • e.g., MAX_WIDTH, PI

30
My personal conventions
  • Hungarian notation (type prefixes)
  • m_ indicates member variables
  • s_ indicates static variables
  • I cant follow conventions in examples
  • You dont have to do what I do
  • Most important thing is consistency

31
Questions about naming conventions?
32
java.lang.Object
  • Every class implicitly extends Object
  • This has benefits
  • Collections and other code can operate on any
    class if they operate on Objects
  • Every class gets Object interface
  • But what is this Object interface?

33
Object methods
  • protected Object clone()
  • public boolean equals(Object o)
  • protected void finalize()
  • public Class getClass()
  • public int hashCode()
  • public String toString()
  • // synchronization methods for a future class

34
clone()
  • protected method
  • Meant to provide a way of creating a (deep) copy
    of a class without knowing its type
  • Associated Cloneable interface
  • Semantics if an Object implements Cloneable,
    then it can be cloned

35
Using clone?
  • List l someList()
  • List l2 new LinkedList()
  • for(Iterator it l.iterator()
  • it.hasNext() )
  • Object obj it.next()
  • Object obj2 ((Cloneable)obj).clone()
  • l2.add(obj2)

36
Cant use clone that way
  • Cloneable is just a tagging interface
  • It doesnt define any methods
  • clone() is in Object
  • Cloneable just says clone() works
  • We shouldnt coerce to Cloneable

37
Using clone, take two?
  • List l someList()
  • List l2 new LinkedList()
  • for(Iterator it lt.iterator()
  • it.hasNext() )
  • Object obj it.next()
  • // we could check obj instanceof Cloneable
  • // but it would fail the same either way
  • Object obj2 obj.clone()
  • l2.add(obj2)

38
Cant use clone that way
  • clone() is protected and can only be accessed by
  • Methods in same package
  • Methods in subclass

39
Using clone, or not
  • clone() was probably originally introduced
    because someone had a problem and didnt think
    enough
  • Now it has been discovered to have rather broken
    semantics
  • Dont use it

40
finalize()
  • Called when the object is about to be
    garbage-collected
  • Used to do last-minute cleanup
  • Not guaranteed to be called
  • There are better ways to clean up
  • Ive never used it

41
getClass()
  • Used to get a Class object
  • Used with reflection API
  • Reflection looking back at oneself
  • Figuring out what a class looks like at runtime
    rather than compile time
  • Sometimes useful for debugging

42
toString()
  • Default implementation returns a String giving
    information about class and memory address of an
    object
  • default toString is unique for each object
  • java.lang.Object_at_b6ece5
  • You should override toString for any class meant
    to be instantiated
  • Very useful for debugging

43
equals and hashCode
  • Two of the most important Object methods
  • Two of the trickiest to override correctly
  • And not just because of typos
  • equals(MyClass c) vs. equals(Object o)
  • hashcode() vs. hashCode()

44
equals(Object o)
  • always means is the same object, i.e. the
    same object in memory
  • .equals() means is an equal object, whatever
    equal means
  • default implementation is
  • e.g., comparing Strings, use .equals()

45
equals(Object o) contract
  • equals is an equivalence relation
  • equals is consistent across calls
  • x.equals(null) returns false

46
Equivalence relation
  • Reflexive
  • x.equals(x) true
  • Symmetric
  • x.equals(y) y.equals(x)
  • Transitive
  • x.equals(y) true, y.equals(z) true ?
    x.equals(z) true

47
Example Point class
  • public class Point
  • protected int x, y
  • // constructor, access methods, ...
  • public boolean equals(Object o)
  • if(!(o instanceof Point))
  • return false
  • Point p (Point)o
  • return ((x p.x) (y p.y))

48
Equivalence and inheritance
  • It is relatively easy to satisfy the equivalence
    relation criteria for a single class
  • It is non-trivial to satisfy the equivalence
    relation for inheritance hierarchies

49
Example ColorPoint class
  • public class ColorPoint extends Point
  • private Color color
  • // constructor, access methods, ...
  • public boolean equals(Object o)
  • // ???
  • How do we override equals?

50
First attempt at equals
  • public boolean equals(Object o)
  • if(!(o instanceof ColorPoint))
  • return false
  • ColorPoint cp (ColorPoint)o
  • return (super.equals(cp)
  • color.equals(cp.color))

51
Symmetry violated
  • Point p new Point(3, 4)
  • ColorPoint cp
  • new ColorPoint(3, 4, Color.RED)
  • boolean fTrue p.equals(cp)
  • boolean fFalse cp.equals(p)

52
Second attempt at equals
  • public boolean equals(Object o)
  • if(o instanceof ColorPoint)
  • ColorPoint cp (ColorPoint)o
  • return (super.equals(o)
  • color.equals(cp.color))
  • else if(o instanceof Point)
  • return super.equals(o)
  • else
  • return false

53
Transitivity violated
  • ColorPoint cp1
  • new ColorPoint(3, 4, Color.BLUE)
  • Point p new Point(3, 4)
  • ColorPoint cp2
  • new ColorPoint(3, 4, Color.RED)
  • boolean fTrue1 cp1.equals(p)
  • boolean fTrue2 p.equals(cp2)
  • boolean fFalse cp1.equals(cp2)

54
Solutions
  • Make ColorPoints equals not compare colors
  • But this negates the whole point of ColorPoint
  • Make ColorPoint not inherit from Point
  • It doesnt really satisfy the is-a relation

55
Questions about equality?
56
hashCode()
  • Provides a good hash on the object
  • Used by HashSet, HashMap, etc.
  • Default implementation returns the objects
    location in memory

57
equals and hashCode??Why are we talking about
these together?
58
Aside hashtable innards
hashtable
(0,1) hash 0
?
(6,9) hash 3
(6,9) hash 3
(7,6) hash 5
(1,-2) hash 5
59
hashCode() contract
  • hashCode is consistent across calls
  • hashCode agrees with equals
  • If two objects are equal, then they have the same
    hash
  • As much as possible, unequal objects have unequal
    hashes
  • Advisable but not requiredcould give everything
    a hash of 0

60
Review of Object methods
  • protected Object clone()
  • public boolean equals(Object o)
  • protected void finalize()
  • public Class getClass()
  • public int hashCode()
  • public String toString()
  • // synchronization methods for a future class

61
Questions?
62
(No Transcript)
Write a Comment
User Comments (0)
About PowerShow.com