Professional Documents
Culture Documents
Java Nots PDF
Java Nots PDF
Review
Exceptions
IO
Review
Interfaces? Interfaces!
• It’s a contract!
• If you must implement ALL the methods
int getNumWheels();
BigRig
sprite.draw(graphics, x, y);
x += xDirection;
y += yDirection;
}
}
Inheritance
Exceptions
I/O
Inheritance
• Making a Game
public class Dude {
public int mp = 0;
Inheritance..
But Wait!
A Wizard does and has everything a
Inheritance?
wizard1.hp += 1;
...
mp -= 10;
grandWizard1.name = “Flash”
grandWizard1.sayName();
((Dude)grandWizard1).sayName();
((Dude)grandWizard1).sayName()
Parent of
Wizard, Elf..
Dude
Subclass
of Dude
Wizard Thief Elf
Subclass of
Grand
Wizard
Wizard
You can only inherit from one class
Dude
Thief Elf
Bad Elf
You can only inherit from one class
Dude
Thief Elf
Bad Elf
You can only inherit from one class
Dude
What if Thief and Elf both implement
• http://java.sun.com/docs/books/tutorial/java/IandI/subclasses.html
• http://home.cogeco.ca/~ve3ll/jatutor5.htm
• http://en.wikipedia.org/wiki/Inheritance_(computer_science)
• http://www.google.com
Exceptions
Exceptions
• NullPointerException
• ArrayIndexOutOfBoundsException
• ClassCastException
• RuntimeException
What is an “Exception”?
• Exception is a class
• Just inherit from it!
public class MyException extends Exception
{
}
Catching an Exception
• What it does
– try to run some code that may throw an exception
– Tell Java what to do if it sees the exception (catch)
try {
get(-1);
main
Rethrowing it
main
doBad
Rethrowing it
main
doBad
get
Rethrowing it
main
doBad
get
Rethrowing it
main
doBad
get Exception
Rethrowing it
main
doBad
get Exception
Rethrowing it
main
doBad Exception
Rethrowing it
main
doBad Exception
Rethrowing it
main Exception
Rethrowing it
main Exception
What it no one catches it?
• If you ran
public static void main(String[] args) throws Exception {
doBad();
}
java.lang.ArrayIndexOutOfBoundsException: -1
at YourClass.get(YourClass.java:50)
at YourClass.doBad(YourClass.java:11)
at YourClass.main(YourClass.java:10)
More Info?
• http://java.sun.com/docs/books/tutorial/essential/exceptions
• http://en.wikipedia.org/wiki/Exceptions
I/O
System.out.println(“some string”);
InputStream
InputStream
new InputStreamReader(stream)
BufferedReader
new BufferedReader(
new InputStreamReader(System.in));
User Input
InputStreamReader ir = new
InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ir);
br.readLine();
FileReader
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
System.out.println(line);
br.close();
}
}
More about I/O
• http://java.sun.com/docs/books/tutorial/essential/io/
Assignment
• Magic Squares
• Read two files
• Check that all rows and columns sum to 15
2 7 6 15
9 5 1 15
4 3 8 15
15 15
15 15 15
For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.