SlideShare a Scribd company logo
1 of 59
Download to read offline
Lecture 7
Review
Exceptions
IO
Review
Interfaces? Interfaces!
• It’s a contract!
• If you must implement ALL the methods
• All fields are final (cannot be changed)
public interface ICar {
boolean isCar = true;
int getNumWheels();
}
BigRig
class BigRig implements ICar {
int getNumWheels() {
return 18;
}
}
That Homework!
• Bouncer draws a Sprite that
– Moves around
– Bounces in a box
• A Sprite is an interface
– You can draw anything
• Mover
– Keeps updating the coordinates of a Sprite
An Oval Sprite
public class Oval implements Sprite {
private int width, height;
private Color color;
public Oval(int width, int height, Color color) {
// set the fields ...
}
public void draw(Graphics surface, int x, int y) {
surface.setColor(color);
surface.fillOval(x, y, width, height);
surface.drawOval(x, y, width, height);
}
...
}
A Mover that doesn’t bounce
public class StraightMover {
private int x, y, xDirection, yDirection;
private Sprite sprite;
public StraightMover(int startX, int startY, Sprite sprite) {
x = startX;
y = startY;
this.sprite = sprite;
}
public void setMovementVector(int xIncrement, int yIncrement) {
xDirection = xIncrement;
yDirection = yIncrement;
}
public void draw(Graphics graphics) {
sprite.draw(graphics, x, y);
x += xDirection;
y += yDirection;
}
}
Inheritance
Exceptions
I/O
Inheritance
Very Very Basic Inheritance
• Making a Game
public class Dude {
public String name;
public int hp = 100
public int mp = 0;
public void sayName() {
System.out.println(name);
}
public void punchFace(Dude target) {
target.hp -= 10;
}
}
Inheritance..
• Now create a Wizard…
public class Wizard {
// ugh, gotta copy and paste
// Dude’s stuff
}
Inheritance?
• Now create a Wizard…
But Wait!
A Wizard does and has everything a
Dude does and has!
Inheritance?
• Now create a Wizard…
Don’t Act Now!
You don’t have to Copy & Paste!
Buy Inheritance!
• Wizard is a subclass of Dude
public class Wizard extends Dude {
}
Buy Inheritance!
• Wizard can use everything* the Dude has!
wizard1.hp += 1;
• Wizard can do everything* Dude can do!
wizard1.punchFace(dude1);
• You can use a Wizard like a Dude too!
dude1.punchface(wizard1);
*except for private fields and methods
Buy Inheritance!
• Now augment a Wizard
public class Wizard extends Dude {
ArrayList<Spell> spells;
public class cast(String spell) {
// cool stuff here
...
mp -= 10;
}
}
Inheriting from inherited classes
• What about a Grand Wizard?
public class GrandWizard extends Wizard {
public void sayName() {
System.out.println(“Grand wizard” + name)
}
}
grandWizard1.name = “Flash”
grandWizard1.sayName();
((Dude)grandWizard1).sayName();
How does Java do that?
• What Java does when it sees
grandWizard1.punchFace(dude1)
1. Look for punchFace()in the GrandWizard class
2. It’s not there! Does GrandWizard have a parent?
3. Look for punchFace()in Wizard class
4. It’s not there! Does Wizard have a parent?
5. Look for punchFace()in Dude class
6. Found it! Call punchFace()
7. Deduct hp from dude1
How does Java do that? pt2
• What Java does when it sees
((Dude)grandWizard1).sayName()
1. Cast to Dude tells Java to start looking in Dude
2. Look for sayName()in Dude class
3. Found it! Call sayName()
What’s going on?
Parent of
Wizard, Elf..
Subclass
of Dude
Subclass of
Wizard
Dude
Wizard Thief Elf
Grand
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
What if Thief and Elf both implement
public void sneakUp()
If they implemented differently,
which sneakUp()does BadElf call?
Java Doesn’t Know!!
Dude
Thief Elf
Bad Elf
Inheritance Summary
• class A extends B {} == A is a subclass of B
• A has all the fields and methods that B has
• A can add it’s own fields and methods
• A can only have 1 parent
• A can replace a parent’s method by re-
implementing it
• If A doesn’t implement something Java
searches ancestors
So much more to learn!
• 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”?
• Event that occurs when something
“unexpected” happens
– null.someMethod();
– (new int[1])[1] = 0;
– int i = “string”;
Why use an Exception?
• To tell the code using your method that
something went wrong
Exception in thread "main"
java.lang.ArrayIndexOutOfBoundsException: 5
at RuntimeException.main(RuntimeException.java:8)
Accessed index 5, which isn’t in the array
The method that called it was main
• Debugging and understanding control flow
How do exceptions “happen”?
• Java doesn’t know what to do, so it
– Creates an Exception object
– Includes some useful information
– “throws” the Exception
• You can create and throw Exceptions too!
public class Exception
• Exception is a class
• Just inherit from it!
public class MyException extends Exception
{
}
• Or use existing ones
– http://rymden.nu/exceptions.html
Warn Java about the Exception
public Object get(int index) throws
ArrayOutOfBoundsException {
If (index < 0 || index >= size())
throw new
ArrayOutOfBoundsException(“”+index);
}
• throws tells Java that get may throw the
ArrayOutOfBoundsException
• throw actually throws the Exception (sorry)
Catching an Exception
• Java now expects code that calls get to deal
with the exception by
– Catching it
– Rethrowing it
Catching it
• 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);
} catch (ArrayOutOfBoundsException err) {
System.out.println(“oh dear!”);
}
Rethrowing it
• Maybe you don’t want to deal with the
Exception
• Tell Java that your method throws it too
void doBad() throws ArrayOutOfBoundsException {
get(-1);
}
Rethrowing it
main
Rethrowing it
doBad
main
Rethrowing it
get
doBad
main
Rethrowing it
get
doBad
main
Rethrowing it
get
doBad
main
Exception
Rethrowing it
get
doBad
main
Exception
Rethrowing it
doBad
main
Exception
Rethrowing it
doBad
main
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 will print that error message you see
Exception in thread "main"
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
We’ve seen Output
System.out.println(“some string”);
The Full Picture
Hard drive Network
100101010101000101 ... InputStream
System.in
‘O’ ‘k’ ‘a’ ‘y’ ‘ ‘ ‘a’ ‘w’ ‘e’ … InputStreamReader
“Okay awesome, cooln” … BufferedReader
InputStream
• InputStream is a stream of bytes
– Read one byte after another using read()
• A byte is just a number
– Data on your hard drive is stored in bytes
– Bytes can be interpreted as characters, numbers..
InputStream stream = System.in;
InputStreamReader
• Reader is a class for character streams
– Read one character after another using read()
• InputStreamReader takes an InputStream and
converts bytes to characters
• Still inconvenient
– Can only read a character at a time
new InputStreamReader(stream)
BufferedReader
• BufferedReader buffers a character stream so
you can read line by line
– String readLine()
new BufferedReader(
new InputStreamReader(System.in));
User Input
InputStreamReader ir = new
InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ir);
br.readLine();
FileReader
• FileReader takes a text file
– converts it into a character stream
– FileReader(“PATH TO FILE”);
• Use this + BufferedReader to read files!
FileReader fr = new FileReader(“readme.txt”);
BufferedReader br = new BufferedReader(fr);
FileReader Code
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class ReadFile {
public static void main(String[] args) throws IOException{
// Path names are relative to project directory (Eclipse Quirk )
FileReader fr = new FileReader("./src/readme");
BufferedReader br = new BufferedReader(fr);
String line = null;
while ((line = br.readLine()) != null) {
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
9 5 1
4 3 8
15
15
15
15
15
15 15 15
Figure by MIT OpenCourseWare.
MIT OpenCourseWare
http://ocw.mit.edu
6.092 Introduction to Programming in Java
January (IAP) 2010
For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.

More Related Content

Similar to LECTURE 7 REVIEW, EXCEPTIONS, IO.pdf

First fare 2011 frc-java-introduction
First fare 2011 frc-java-introductionFirst fare 2011 frc-java-introduction
First fare 2011 frc-java-introductionOregon FIRST Robotics
 
Intro to Java for C++ Developers
Intro to Java for C++ DevelopersIntro to Java for C++ Developers
Intro to Java for C++ DevelopersZachary Blair
 
Multi-threading in the modern era: Vertx Akka and Quasar
Multi-threading in the modern era: Vertx Akka and QuasarMulti-threading in the modern era: Vertx Akka and Quasar
Multi-threading in the modern era: Vertx Akka and QuasarGal Marder
 
GOTO Night with Charles Nutter Slides
GOTO Night with Charles Nutter SlidesGOTO Night with Charles Nutter Slides
GOTO Night with Charles Nutter SlidesAlexandra Masterson
 
Atlassian Groovy Plugins
Atlassian Groovy PluginsAtlassian Groovy Plugins
Atlassian Groovy PluginsPaul King
 
Java Programming and J2ME: The Basics
Java Programming and J2ME: The BasicsJava Programming and J2ME: The Basics
Java Programming and J2ME: The Basicstosine
 
Adv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdfAdv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdfKALAISELVI P
 
Java 8 and beyond, a scala story
Java 8 and beyond, a scala storyJava 8 and beyond, a scala story
Java 8 and beyond, a scala storyittaiz
 
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...Charles Nutter
 
The State of Managed Runtimes 2013, by Attila Szegedi
The State of Managed Runtimes 2013, by Attila SzegediThe State of Managed Runtimes 2013, by Attila Szegedi
The State of Managed Runtimes 2013, by Attila SzegediZeroTurnaround
 
Beyond JVM - YOW! Brisbane 2013
Beyond JVM - YOW! Brisbane 2013Beyond JVM - YOW! Brisbane 2013
Beyond JVM - YOW! Brisbane 2013Charles Nutter
 
JAVA VIRTUAL MACHINE
JAVA VIRTUAL MACHINEJAVA VIRTUAL MACHINE
JAVA VIRTUAL MACHINEAadil Ansari
 
Eric Lafortune - The Jack and Jill build system
Eric Lafortune - The Jack and Jill build systemEric Lafortune - The Jack and Jill build system
Eric Lafortune - The Jack and Jill build systemGuardSquare
 

Similar to LECTURE 7 REVIEW, EXCEPTIONS, IO.pdf (20)

Java Tutorial
Java Tutorial Java Tutorial
Java Tutorial
 
55 New Features in Java 7
55 New Features in Java 755 New Features in Java 7
55 New Features in Java 7
 
First fare 2011 frc-java-introduction
First fare 2011 frc-java-introductionFirst fare 2011 frc-java-introduction
First fare 2011 frc-java-introduction
 
Intro to Java for C++ Developers
Intro to Java for C++ DevelopersIntro to Java for C++ Developers
Intro to Java for C++ Developers
 
Multi-threading in the modern era: Vertx Akka and Quasar
Multi-threading in the modern era: Vertx Akka and QuasarMulti-threading in the modern era: Vertx Akka and Quasar
Multi-threading in the modern era: Vertx Akka and Quasar
 
Scala Introduction
Scala IntroductionScala Introduction
Scala Introduction
 
GOTO Night with Charles Nutter Slides
GOTO Night with Charles Nutter SlidesGOTO Night with Charles Nutter Slides
GOTO Night with Charles Nutter Slides
 
Atlassian Groovy Plugins
Atlassian Groovy PluginsAtlassian Groovy Plugins
Atlassian Groovy Plugins
 
Java Programming and J2ME: The Basics
Java Programming and J2ME: The BasicsJava Programming and J2ME: The Basics
Java Programming and J2ME: The Basics
 
Adv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdfAdv java unit 1 M.Sc CS.pdf
Adv java unit 1 M.Sc CS.pdf
 
Java 8 and beyond, a scala story
Java 8 and beyond, a scala storyJava 8 and beyond, a scala story
Java 8 and beyond, a scala story
 
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
Øredev 2011 - JVM JIT for Dummies (What the JVM Does With Your Bytecode When ...
 
Java
JavaJava
Java
 
The State of Managed Runtimes 2013, by Attila Szegedi
The State of Managed Runtimes 2013, by Attila SzegediThe State of Managed Runtimes 2013, by Attila Szegedi
The State of Managed Runtimes 2013, by Attila Szegedi
 
Beyond JVM - YOW! Brisbane 2013
Beyond JVM - YOW! Brisbane 2013Beyond JVM - YOW! Brisbane 2013
Beyond JVM - YOW! Brisbane 2013
 
core java
core javacore java
core java
 
JavaScript Good Practices
JavaScript Good PracticesJavaScript Good Practices
JavaScript Good Practices
 
JAVA VIRTUAL MACHINE
JAVA VIRTUAL MACHINEJAVA VIRTUAL MACHINE
JAVA VIRTUAL MACHINE
 
Exceptions
ExceptionsExceptions
Exceptions
 
Eric Lafortune - The Jack and Jill build system
Eric Lafortune - The Jack and Jill build systemEric Lafortune - The Jack and Jill build system
Eric Lafortune - The Jack and Jill build system
 

Recently uploaded

UNIT-II-ENGINE AUXILIARY SYSTEMS &TURBOCHARGER
UNIT-II-ENGINE AUXILIARY SYSTEMS &TURBOCHARGERUNIT-II-ENGINE AUXILIARY SYSTEMS &TURBOCHARGER
UNIT-II-ENGINE AUXILIARY SYSTEMS &TURBOCHARGERDineshKumar4165
 
Call me @ 9892124323 Call Girl in Andheri East With Free Home Delivery
Call me @ 9892124323 Call Girl in Andheri East With Free Home DeliveryCall me @ 9892124323 Call Girl in Andheri East With Free Home Delivery
Call me @ 9892124323 Call Girl in Andheri East With Free Home DeliveryPooja Nehwal
 
2024 WRC Hyundai World Rally Team’s i20 N Rally1 Hybrid
2024 WRC Hyundai World Rally Team’s i20 N Rally1 Hybrid2024 WRC Hyundai World Rally Team’s i20 N Rally1 Hybrid
2024 WRC Hyundai World Rally Team’s i20 N Rally1 HybridHyundai Motor Group
 
BLUE VEHICLES the kids picture show 2024
BLUE VEHICLES the kids picture show 2024BLUE VEHICLES the kids picture show 2024
BLUE VEHICLES the kids picture show 2024AHOhOops1
 
Hot And Sexy 🥵 Call Girls Delhi Daryaganj {9711199171} Ira Malik High class G...
Hot And Sexy 🥵 Call Girls Delhi Daryaganj {9711199171} Ira Malik High class G...Hot And Sexy 🥵 Call Girls Delhi Daryaganj {9711199171} Ira Malik High class G...
Hot And Sexy 🥵 Call Girls Delhi Daryaganj {9711199171} Ira Malik High class G...shivangimorya083
 
(8264348440) 🔝 Call Girls In Shaheen Bagh 🔝 Delhi NCR
(8264348440) 🔝 Call Girls In Shaheen Bagh 🔝 Delhi NCR(8264348440) 🔝 Call Girls In Shaheen Bagh 🔝 Delhi NCR
(8264348440) 🔝 Call Girls In Shaheen Bagh 🔝 Delhi NCRsoniya singh
 
Crash Vehicle Emergency Rescue Slideshow.ppt
Crash Vehicle Emergency Rescue Slideshow.pptCrash Vehicle Emergency Rescue Slideshow.ppt
Crash Vehicle Emergency Rescue Slideshow.pptVlademirGebDubouzet1
 
꧁ ୨⎯Call Girls In Ashok Vihar, New Delhi **✿❀7042364481❀✿**Escorts ServiCes C...
꧁ ୨⎯Call Girls In Ashok Vihar, New Delhi **✿❀7042364481❀✿**Escorts ServiCes C...꧁ ୨⎯Call Girls In Ashok Vihar, New Delhi **✿❀7042364481❀✿**Escorts ServiCes C...
꧁ ୨⎯Call Girls In Ashok Vihar, New Delhi **✿❀7042364481❀✿**Escorts ServiCes C...Hot Call Girls In Sector 58 (Noida)
 
如何办理(UQ毕业证书)昆士兰大学毕业证毕业证成绩单原版一比一
如何办理(UQ毕业证书)昆士兰大学毕业证毕业证成绩单原版一比一如何办理(UQ毕业证书)昆士兰大学毕业证毕业证成绩单原版一比一
如何办理(UQ毕业证书)昆士兰大学毕业证毕业证成绩单原版一比一hnfusn
 
GREEN VEHICLES the kids picture show 2024
GREEN VEHICLES the kids picture show 2024GREEN VEHICLES the kids picture show 2024
GREEN VEHICLES the kids picture show 2024AHOhOops1
 
UNIT-1-VEHICLE STRUCTURE AND ENGINES.ppt
UNIT-1-VEHICLE STRUCTURE AND ENGINES.pptUNIT-1-VEHICLE STRUCTURE AND ENGINES.ppt
UNIT-1-VEHICLE STRUCTURE AND ENGINES.pptDineshKumar4165
 
UNIT-V-ELECTRIC AND HYBRID VEHICLES.pptx
UNIT-V-ELECTRIC AND HYBRID VEHICLES.pptxUNIT-V-ELECTRIC AND HYBRID VEHICLES.pptx
UNIT-V-ELECTRIC AND HYBRID VEHICLES.pptxDineshKumar4165
 
UNOSAFE ELEVATOR PRIVATE LTD BANGALORE BROUCHER
UNOSAFE ELEVATOR PRIVATE LTD BANGALORE BROUCHERUNOSAFE ELEVATOR PRIVATE LTD BANGALORE BROUCHER
UNOSAFE ELEVATOR PRIVATE LTD BANGALORE BROUCHERunosafeads
 
Vip Hot Call Girls 🫤 Mahipalpur ➡️ 9711199171 ➡️ Delhi 🫦 Whatsapp Number
Vip Hot Call Girls 🫤 Mahipalpur ➡️ 9711199171 ➡️ Delhi 🫦 Whatsapp NumberVip Hot Call Girls 🫤 Mahipalpur ➡️ 9711199171 ➡️ Delhi 🫦 Whatsapp Number
Vip Hot Call Girls 🫤 Mahipalpur ➡️ 9711199171 ➡️ Delhi 🫦 Whatsapp Numberkumarajju5765
 
定制(UW毕业证书)华盛顿大学毕业证成绩单原版一比一
定制(UW毕业证书)华盛顿大学毕业证成绩单原版一比一定制(UW毕业证书)华盛顿大学毕业证成绩单原版一比一
定制(UW毕业证书)华盛顿大学毕业证成绩单原版一比一ffhuih11ff
 
John Deere 300 3029 4039 4045 6059 6068 Engine Operation and Service Manual
John Deere 300 3029 4039 4045 6059 6068 Engine Operation and Service ManualJohn Deere 300 3029 4039 4045 6059 6068 Engine Operation and Service Manual
John Deere 300 3029 4039 4045 6059 6068 Engine Operation and Service ManualExcavator
 
John Deere 200lc Excavator Operation And Tests Repair Manual.pdf
John Deere 200lc Excavator Operation And Tests Repair Manual.pdfJohn Deere 200lc Excavator Operation And Tests Repair Manual.pdf
John Deere 200lc Excavator Operation And Tests Repair Manual.pdfExcavator
 

Recently uploaded (20)

UNIT-II-ENGINE AUXILIARY SYSTEMS &TURBOCHARGER
UNIT-II-ENGINE AUXILIARY SYSTEMS &TURBOCHARGERUNIT-II-ENGINE AUXILIARY SYSTEMS &TURBOCHARGER
UNIT-II-ENGINE AUXILIARY SYSTEMS &TURBOCHARGER
 
Call me @ 9892124323 Call Girl in Andheri East With Free Home Delivery
Call me @ 9892124323 Call Girl in Andheri East With Free Home DeliveryCall me @ 9892124323 Call Girl in Andheri East With Free Home Delivery
Call me @ 9892124323 Call Girl in Andheri East With Free Home Delivery
 
2024 WRC Hyundai World Rally Team’s i20 N Rally1 Hybrid
2024 WRC Hyundai World Rally Team’s i20 N Rally1 Hybrid2024 WRC Hyundai World Rally Team’s i20 N Rally1 Hybrid
2024 WRC Hyundai World Rally Team’s i20 N Rally1 Hybrid
 
BLUE VEHICLES the kids picture show 2024
BLUE VEHICLES the kids picture show 2024BLUE VEHICLES the kids picture show 2024
BLUE VEHICLES the kids picture show 2024
 
Hot And Sexy 🥵 Call Girls Delhi Daryaganj {9711199171} Ira Malik High class G...
Hot And Sexy 🥵 Call Girls Delhi Daryaganj {9711199171} Ira Malik High class G...Hot And Sexy 🥵 Call Girls Delhi Daryaganj {9711199171} Ira Malik High class G...
Hot And Sexy 🥵 Call Girls Delhi Daryaganj {9711199171} Ira Malik High class G...
 
(8264348440) 🔝 Call Girls In Shaheen Bagh 🔝 Delhi NCR
(8264348440) 🔝 Call Girls In Shaheen Bagh 🔝 Delhi NCR(8264348440) 🔝 Call Girls In Shaheen Bagh 🔝 Delhi NCR
(8264348440) 🔝 Call Girls In Shaheen Bagh 🔝 Delhi NCR
 
Crash Vehicle Emergency Rescue Slideshow.ppt
Crash Vehicle Emergency Rescue Slideshow.pptCrash Vehicle Emergency Rescue Slideshow.ppt
Crash Vehicle Emergency Rescue Slideshow.ppt
 
꧁ ୨⎯Call Girls In Ashok Vihar, New Delhi **✿❀7042364481❀✿**Escorts ServiCes C...
꧁ ୨⎯Call Girls In Ashok Vihar, New Delhi **✿❀7042364481❀✿**Escorts ServiCes C...꧁ ୨⎯Call Girls In Ashok Vihar, New Delhi **✿❀7042364481❀✿**Escorts ServiCes C...
꧁ ୨⎯Call Girls In Ashok Vihar, New Delhi **✿❀7042364481❀✿**Escorts ServiCes C...
 
如何办理(UQ毕业证书)昆士兰大学毕业证毕业证成绩单原版一比一
如何办理(UQ毕业证书)昆士兰大学毕业证毕业证成绩单原版一比一如何办理(UQ毕业证书)昆士兰大学毕业证毕业证成绩单原版一比一
如何办理(UQ毕业证书)昆士兰大学毕业证毕业证成绩单原版一比一
 
GREEN VEHICLES the kids picture show 2024
GREEN VEHICLES the kids picture show 2024GREEN VEHICLES the kids picture show 2024
GREEN VEHICLES the kids picture show 2024
 
UNIT-1-VEHICLE STRUCTURE AND ENGINES.ppt
UNIT-1-VEHICLE STRUCTURE AND ENGINES.pptUNIT-1-VEHICLE STRUCTURE AND ENGINES.ppt
UNIT-1-VEHICLE STRUCTURE AND ENGINES.ppt
 
UNIT-V-ELECTRIC AND HYBRID VEHICLES.pptx
UNIT-V-ELECTRIC AND HYBRID VEHICLES.pptxUNIT-V-ELECTRIC AND HYBRID VEHICLES.pptx
UNIT-V-ELECTRIC AND HYBRID VEHICLES.pptx
 
UNOSAFE ELEVATOR PRIVATE LTD BANGALORE BROUCHER
UNOSAFE ELEVATOR PRIVATE LTD BANGALORE BROUCHERUNOSAFE ELEVATOR PRIVATE LTD BANGALORE BROUCHER
UNOSAFE ELEVATOR PRIVATE LTD BANGALORE BROUCHER
 
(NEHA) Call Girls Pushkar Booking Open 8617697112 Pushkar Escorts
(NEHA) Call Girls Pushkar Booking Open 8617697112 Pushkar Escorts(NEHA) Call Girls Pushkar Booking Open 8617697112 Pushkar Escorts
(NEHA) Call Girls Pushkar Booking Open 8617697112 Pushkar Escorts
 
Vip Hot Call Girls 🫤 Mahipalpur ➡️ 9711199171 ➡️ Delhi 🫦 Whatsapp Number
Vip Hot Call Girls 🫤 Mahipalpur ➡️ 9711199171 ➡️ Delhi 🫦 Whatsapp NumberVip Hot Call Girls 🫤 Mahipalpur ➡️ 9711199171 ➡️ Delhi 🫦 Whatsapp Number
Vip Hot Call Girls 🫤 Mahipalpur ➡️ 9711199171 ➡️ Delhi 🫦 Whatsapp Number
 
定制(UW毕业证书)华盛顿大学毕业证成绩单原版一比一
定制(UW毕业证书)华盛顿大学毕业证成绩单原版一比一定制(UW毕业证书)华盛顿大学毕业证成绩单原版一比一
定制(UW毕业证书)华盛顿大学毕业证成绩单原版一比一
 
sauth delhi call girls in Connaught Place🔝 9953056974 🔝 escort Service
sauth delhi call girls in  Connaught Place🔝 9953056974 🔝 escort Servicesauth delhi call girls in  Connaught Place🔝 9953056974 🔝 escort Service
sauth delhi call girls in Connaught Place🔝 9953056974 🔝 escort Service
 
Hotel Escorts Sushant Golf City - 9548273370 Call Girls Service in Lucknow, c...
Hotel Escorts Sushant Golf City - 9548273370 Call Girls Service in Lucknow, c...Hotel Escorts Sushant Golf City - 9548273370 Call Girls Service in Lucknow, c...
Hotel Escorts Sushant Golf City - 9548273370 Call Girls Service in Lucknow, c...
 
John Deere 300 3029 4039 4045 6059 6068 Engine Operation and Service Manual
John Deere 300 3029 4039 4045 6059 6068 Engine Operation and Service ManualJohn Deere 300 3029 4039 4045 6059 6068 Engine Operation and Service Manual
John Deere 300 3029 4039 4045 6059 6068 Engine Operation and Service Manual
 
John Deere 200lc Excavator Operation And Tests Repair Manual.pdf
John Deere 200lc Excavator Operation And Tests Repair Manual.pdfJohn Deere 200lc Excavator Operation And Tests Repair Manual.pdf
John Deere 200lc Excavator Operation And Tests Repair Manual.pdf
 

LECTURE 7 REVIEW, EXCEPTIONS, IO.pdf

  • 3. Interfaces? Interfaces! • It’s a contract! • If you must implement ALL the methods • All fields are final (cannot be changed) public interface ICar { boolean isCar = true; int getNumWheels(); }
  • 4. BigRig class BigRig implements ICar { int getNumWheels() { return 18; } }
  • 5. That Homework! • Bouncer draws a Sprite that – Moves around – Bounces in a box • A Sprite is an interface – You can draw anything • Mover – Keeps updating the coordinates of a Sprite
  • 6. An Oval Sprite public class Oval implements Sprite { private int width, height; private Color color; public Oval(int width, int height, Color color) { // set the fields ... } public void draw(Graphics surface, int x, int y) { surface.setColor(color); surface.fillOval(x, y, width, height); surface.drawOval(x, y, width, height); } ... }
  • 7. A Mover that doesn’t bounce public class StraightMover { private int x, y, xDirection, yDirection; private Sprite sprite; public StraightMover(int startX, int startY, Sprite sprite) { x = startX; y = startY; this.sprite = sprite; } public void setMovementVector(int xIncrement, int yIncrement) { xDirection = xIncrement; yDirection = yIncrement; } public void draw(Graphics graphics) { sprite.draw(graphics, x, y); x += xDirection; y += yDirection; } }
  • 10. Very Very Basic Inheritance • Making a Game public class Dude { public String name; public int hp = 100 public int mp = 0; public void sayName() { System.out.println(name); } public void punchFace(Dude target) { target.hp -= 10; } }
  • 11. Inheritance.. • Now create a Wizard… public class Wizard { // ugh, gotta copy and paste // Dude’s stuff }
  • 12. Inheritance? • Now create a Wizard… But Wait! A Wizard does and has everything a Dude does and has!
  • 13. Inheritance? • Now create a Wizard… Don’t Act Now! You don’t have to Copy & Paste!
  • 14. Buy Inheritance! • Wizard is a subclass of Dude public class Wizard extends Dude { }
  • 15. Buy Inheritance! • Wizard can use everything* the Dude has! wizard1.hp += 1; • Wizard can do everything* Dude can do! wizard1.punchFace(dude1); • You can use a Wizard like a Dude too! dude1.punchface(wizard1); *except for private fields and methods
  • 16. Buy Inheritance! • Now augment a Wizard public class Wizard extends Dude { ArrayList<Spell> spells; public class cast(String spell) { // cool stuff here ... mp -= 10; } }
  • 17. Inheriting from inherited classes • What about a Grand Wizard? public class GrandWizard extends Wizard { public void sayName() { System.out.println(“Grand wizard” + name) } } grandWizard1.name = “Flash” grandWizard1.sayName(); ((Dude)grandWizard1).sayName();
  • 18. How does Java do that? • What Java does when it sees grandWizard1.punchFace(dude1) 1. Look for punchFace()in the GrandWizard class 2. It’s not there! Does GrandWizard have a parent? 3. Look for punchFace()in Wizard class 4. It’s not there! Does Wizard have a parent? 5. Look for punchFace()in Dude class 6. Found it! Call punchFace() 7. Deduct hp from dude1
  • 19. How does Java do that? pt2 • What Java does when it sees ((Dude)grandWizard1).sayName() 1. Cast to Dude tells Java to start looking in Dude 2. Look for sayName()in Dude class 3. Found it! Call sayName()
  • 20. What’s going on? Parent of Wizard, Elf.. Subclass of Dude Subclass of Wizard Dude Wizard Thief Elf Grand Wizard
  • 21. You can only inherit from one class Dude Thief Elf Bad Elf
  • 22. You can only inherit from one class Dude Thief Elf Bad Elf
  • 23. You can only inherit from one class What if Thief and Elf both implement public void sneakUp() If they implemented differently, which sneakUp()does BadElf call? Java Doesn’t Know!! Dude Thief Elf Bad Elf
  • 24. Inheritance Summary • class A extends B {} == A is a subclass of B • A has all the fields and methods that B has • A can add it’s own fields and methods • A can only have 1 parent • A can replace a parent’s method by re- implementing it • If A doesn’t implement something Java searches ancestors
  • 25. So much more to learn! • 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
  • 28. What is an “Exception”? • Event that occurs when something “unexpected” happens – null.someMethod(); – (new int[1])[1] = 0; – int i = “string”;
  • 29. Why use an Exception? • To tell the code using your method that something went wrong Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 5 at RuntimeException.main(RuntimeException.java:8) Accessed index 5, which isn’t in the array The method that called it was main • Debugging and understanding control flow
  • 30. How do exceptions “happen”? • Java doesn’t know what to do, so it – Creates an Exception object – Includes some useful information – “throws” the Exception • You can create and throw Exceptions too!
  • 31. public class Exception • Exception is a class • Just inherit from it! public class MyException extends Exception { } • Or use existing ones – http://rymden.nu/exceptions.html
  • 32. Warn Java about the Exception public Object get(int index) throws ArrayOutOfBoundsException { If (index < 0 || index >= size()) throw new ArrayOutOfBoundsException(“”+index); } • throws tells Java that get may throw the ArrayOutOfBoundsException • throw actually throws the Exception (sorry)
  • 33. Catching an Exception • Java now expects code that calls get to deal with the exception by – Catching it – Rethrowing it
  • 34. Catching it • 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); } catch (ArrayOutOfBoundsException err) { System.out.println(“oh dear!”); }
  • 35. Rethrowing it • Maybe you don’t want to deal with the Exception • Tell Java that your method throws it too void doBad() throws ArrayOutOfBoundsException { get(-1); }
  • 46. What it no one catches it? • If you ran public static void main(String[] args) throws Exception { doBad(); } • Java will print that error message you see Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: -1 at YourClass.get(YourClass.java:50) at YourClass.doBad(YourClass.java:11) at YourClass.main(YourClass.java:10)
  • 48. I/O
  • 50. The Full Picture Hard drive Network 100101010101000101 ... InputStream System.in ‘O’ ‘k’ ‘a’ ‘y’ ‘ ‘ ‘a’ ‘w’ ‘e’ … InputStreamReader “Okay awesome, cooln” … BufferedReader
  • 51. InputStream • InputStream is a stream of bytes – Read one byte after another using read() • A byte is just a number – Data on your hard drive is stored in bytes – Bytes can be interpreted as characters, numbers.. InputStream stream = System.in;
  • 52. InputStreamReader • Reader is a class for character streams – Read one character after another using read() • InputStreamReader takes an InputStream and converts bytes to characters • Still inconvenient – Can only read a character at a time new InputStreamReader(stream)
  • 53. BufferedReader • BufferedReader buffers a character stream so you can read line by line – String readLine() new BufferedReader( new InputStreamReader(System.in));
  • 54. User Input InputStreamReader ir = new InputStreamReader(System.in); BufferedReader br = new BufferedReader(ir); br.readLine();
  • 55. FileReader • FileReader takes a text file – converts it into a character stream – FileReader(“PATH TO FILE”); • Use this + BufferedReader to read files! FileReader fr = new FileReader(“readme.txt”); BufferedReader br = new BufferedReader(fr);
  • 56. FileReader Code import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; public class ReadFile { public static void main(String[] args) throws IOException{ // Path names are relative to project directory (Eclipse Quirk ) FileReader fr = new FileReader("./src/readme"); BufferedReader br = new BufferedReader(fr); String line = null; while ((line = br.readLine()) != null) { System.out.println(line); } br.close(); } }
  • 57. More about I/O • http://java.sun.com/docs/books/tutorial/essential/io/
  • 58. Assignment • Magic Squares • Read two files • Check that all rows and columns sum to 15 2 7 6 9 5 1 4 3 8 15 15 15 15 15 15 15 15 Figure by MIT OpenCourseWare.
  • 59. MIT OpenCourseWare http://ocw.mit.edu 6.092 Introduction to Programming in Java January (IAP) 2010 For information about citing these materials or our Terms of Use, visit: http://ocw.mit.edu/terms.