Transcript .ppt

Announcements
•
•
•
•
E1 due today
P4 due on Thursday
P5 handed out this week
Future Topics:
–
–
–
–
–
–
Threads, Synchronization
Applets
Recursion
A bit of C
Pointers
...
CS 100
Lecture 16
1
Today’s Topics
• Exceptions
• Try/Catch
• The abstract modifier, Brief introduction to
interfaces
CS 100
Lecture 16
2
Exceptions
• A way to control the flow of a program
• An exception is an object that defines an
unusual (error) situation
• Exceptions are thrown by the
program/runtime and can be caught and
handled
• Java has many pre-defined exceptions
CS 100
Lecture 16
3
Why Worry?
• Exceptions help to point out errors
• Many predefined classes have exceptions -useful
• Some programs have a requirement that they
should ‘never’ crash -- exceptions help to
facilitate this
CS 100
Lecture 16
4
Uncaught Exceptions
• If an exception is not handled, then the program
terminates, producing a message indicating what
the exception was
• Example: divide by 0 error in the following
public static void main(String[] args) {
int numer = 10; int denom = 0;
System.out.println(numer / denom);
}
CS 100
Lecture 16
5
What if we do want to catch it? -- try
• The try statement indicates a block of
statements that may throw exceptions
• The catch clause indicates what to do with
them.
• There can be multiple catch clauses
• Each is called an exception handler
CS 100
Lecture 16
6
The try statement -- syntax
try {
statements
} catch (exceptionclass1 variable1) {
statements2
} catch (exceptionclass2 variable2) {
statements3
} catch . . .
CS 100
Lecture 16
7
What can we gather?
• Exceptions are objects! So they have a class
(type)
• Java has a class Exception, and specific
exceptions are subclasses thereof
• These classes have methods associated with
them, including getMessage. . .
• . . .that explains the reason the exception was
thrown
• Check out Appendix M in text to see many
exceptions in Java API
CS 100
Lecture 16
8
Example -- catching input error
try {
number = Integer.parseInt(stdin.readLine());
} catch (NumberFormatException exception) {
System.out.println(“Invalid input. Try again.”);
} catch (IOException exception) {
System.out.println(“Input error. Terminating.”);
System.out.exit(0);
}
CS 100
Lecture 16
9
The throw statement
• Exceptions can propagate.
• So, if an exception is generated, and not handled
immediately, it is propagated to the calling
method.
• To be handled there, the method that produced it
must have been invoked inside an appropriate
try/catch block
• If a method is checked but not handled, then
need to add a throws clause to the method
header
CS 100
Lecture 16
10
Defining our own exceptions
Public class Throw_Demo {
public static void main(String[] args) throws Ooops {
Ooops problem = new Ooops(“Alert!”);
throw problem;
// never get here
}
}
class Ooops extends IOException {
Ooops(String message) {
super(message);
}
Lecture 16
11
} CS 100
Method/Constructor overloading
• We know the steps that occur when a method is
invoked
• But, in fact, the name of the method is not
sufficient to determine which method definition
to use
• You can use the same method name for multiple
methods -- method overloading
• Need info other than name to uniquely identify
methods
CS 100
Lecture 16
12
Method signatures
method name
+ number of parameters
+ type of parameters
+ order of parameters
= its signature
CS 100
println (String s)
println (int I)
println (double d)
println (char c)
println (boolean b)
are all different methods
So,
System.out.println(“hi!”)
and
System.out.println(5);
actually invoke different methods
Lecture 16
13
Overloading constructors
• Overloading constructors can be very useful
• Provides multiple ways to create and
initialize and object of a given type
• As long as the signatures are different, the
compiler will know which constructor you
mean to use at any given call
CS 100
Lecture 16
14
Example of overloaded constructors
Public class Rectangle {
int length; int width; int shade;
public Rectangle() {
length = 10; width = 20; shade = 50; }
public Rectangle(int side1, int side2) {
length = side1; width = side2; shade = 0; }
public Rectangle (int side1, int side2, int level) {
length = side1; width = side2; shade = level; }
public int area() {
return length*width;}
Lecture 16
} CS 100
15
Use of previous constructors
int a, b, c;
Rectangle r1 = new Rectangle();
Rectangle r2 = new Rectangle(3, 5, 10);
Rectangle r3 = new Rectangle(4, 6);
a = r3.area();
b = r2.area();
c = r1.area();
CS 100
Lecture 16
16
Overloading vs. overriding methods
• What’s the difference between overloading
methods and overriding methods?
• Can methods be both overloaded and
overridden?
CS 100
Lecture 16
17
Abstract
•
•
•
•
An abstract class cannot be instantiated
Abstract classes contain abstract methods
Abstract methods do not contain implementations
Used in a class hierarchy where a class defines
just part of its implementation and expects its
subclasses to fill in the rest
• A nonabstract class derived from an abstract class
MUST override all of its parent’s abstract
methods
CS 100
Lecture 16
18
Example
abstract class Food {
abstract public String slogan(); }
class Chocolate extends Food {
public String slogan() {
return “Food of the gods.”; }
}
CS 100
Lecture 16
19
Abstract and non-abstract
• Abstract classes can contain nonabstract
methods (that have implementations) along with
abstract methods
• The subclasses of this class will inherit the
nonabstract components just like normal
• Note that abstract final and abstract static
make no sense for methods
• If a subclass does not override all abstract
method’s of a parent class, then the subclass
must be declared abstract
CS 100
Lecture 16
20
Interfaces, briefly
• An interface is a collection of constants and
abstract methods
• Syntax:
interface interfaceName {
constants-declarations
abstract-method-declaration}
• A class implements an interface by providing
method implementations for all the methods listed.
• Syntax:
class className implements interfaceName {
method-implementations }
CS 100
Lecture 16
21
Interfaces get very tricky
• Java has only single inheritance
• Interfaces can be used to mimic multiple
inheritance (a bit)
• Also very useful for encapsulation and
information hiding
• Will cover more on interfaces later this week (?)
• See Chapter 9 in text for more info right now
CS 100
Lecture 16
22