Download Adam Gerber, PhD

Document related concepts
no text concepts found
Transcript
Agenda Lec05
Exceptions API
Reference- and Type-Anonymity
Swing
Review
Review:
Aperture and underlying object
Object
Number
Double
S
C
A reference is an aperture.
A reference is an aperture.
Object obj = new Double(5.87);
reference
Object
Underlying
object
Double
A reference is an aperture.
Number num = new Double(89.17);
reference
Underlying
object
Number
Double
A reference is an aperture.
Double dub = new Double(72.17);
reference
Double
Underlying
object
Double
A reference is an aperture.
Comparable com = new Double(72.17);
reference
C
Underlying
object
Double
The only way to create an object is
to use the new keyword (exception
to this rule is String)
Once instantiated on the heap,
that object's type can NEVER
change.
You may widen or narrow the
aperture only. casting/CastObjectsDriver
Exceptions:
Checked versus Unchecked
Exceptions
http://www.ibm.com/developerwo
rks/java/library/j-jtp05254/
Probable Source
Error
Within your
control
Probable Source Checked
User should
Recover
NO
JVM
NO
NO
Programmer
NO
NO
RuntimeException YES
(unchecked)
All other
exceptions
(checked)
NO
User, External
YES
resources, Thread
YES
Example of Error: System-out-of-memory Error
Examples of RuntimeException: ClassCastException, NumberFormatException.
Example of checked Exceptions: EOFExcception,
Your program
running in JVM
Hosting system
Green = unchecked
Blue = checked
Situations which cause Exceptions
(or Errors) to be thrown
• An internal Error occurs in the VM
(OutOfMemoryError) this can happen if the gc
can not catch up with your program.
• An unchecked Exception is generated and
thrown (ArrayIndexOutOfBounds)
• A checked Exception is thrown (EOFException)
• You purposefully throw an Exception.
Exception sequence
• Once an exception is generated, the execution
sequence immediately terminates until the
exception is caught (or propagates up the call
stack to the VM). In practice that means that
any code following your statement which
threatens to throw an exception will NOT be
executed if an exception occurs. No return
value!
• An exception is thrown up the call stack
See debug dir examples
Some Java naming wierdness in the
Exception Handling API
• Despite having the 'able' suffix, Throwable is a
class, not an interface.
• Errors are considered part of the "Exception
Handling" API
• All Exceptions and Errors occur at Runtime, so
RuntimeException is a useless name.
Some things to remember about
Exceptions
• Anything that inherets from RuntimeException
is unchecked.
• Why did the engineers of the Java language
decide to create Unchecked Exceptions?
Checked versus Unchecked
Unchecked:
You are the master of your JVM green-zone and therefore
you are responsible for ensuring there are no exceptions in
your code which are ultimately your responsibility. If the
Java language required all methods which threaten to throw
an exception, including those in the green-zone, then your
code would be riddled with try/catch blocks rendering it
effectively unreadable. Imagine if every time you wanted to
call an instance method from an implicit parameter
(reference), you were required to check a
NullPointerException.
Checked versus Unchecked
Checked:
Any time you attempt to leave the relative safety of the
green-zone of the JVM, you enter an unpredictable space
where things can and do go wrong. This includes,
unpredictable user input; servers, networks, and databases
that are unavailable or down; I/O in the users file system.
The world of concurrency can be an unsafe one as well, so
Java has many checked methods in the concurrency API.
Java checks these exceptions to impose discipline on the
programmer, so that all calls made beyond the JVM greenzone are recoverable from the chaos of the exterior
environment.
The debate over checked and
unchecked
See:
http://www.ibm.com/developerworks/java/libra
ry/j-jtp05254/
1/ are you dealing with user, system, or remote
data?
2/ should your user recover?
If yes, it'll probably threaten to throw a checked
exception
If you create your own Exception
class, it should probably be
checked
Most unchecked exceptions are the “programers
fault” and these situations have already been
covered by the SDK.
Source Code Online
Source Code Online
• Please avail yourselves of the many excellent
sources for source code, both full applications
and snippets.
• http://stackoverflow.com/ (best for snippets)
• GitHub.com
• BitBucket.org
• http://www.planet-source-code.com/ (best for
full apps)
• http://www.freewarejava.com/
• http://www.javagalaxy.com/
Guidelines for using found source code
• If you know the URL where you got it, cite like
so:
– //http://stackoverflow.com/questions/26305/how
-can-i-play-sound-in-java
• Don't copy an entire application; that is
plagiarism.
• Use found source code within reason.
• Minimum 60% of your app must be your own
code.
Reflection
Reflection
• Very useful when first learning an OO
language.
• Reference anonymous - gravity
https://www.youtube.com/watch?v=vKW-Gd_S_xc
Reflection
• Reflection allows you to inspect the type
(class) of the implicit parameter at runtime.
• We will use reflection to gain a deeper
understanding of polymorphism and the java
event model.
Every class has a class object which you can
access like so: java.util.Date.class, or like so:
Class.forName(strFullyQualifiedClass);
See reflection example
Reflection
Name of Driver
implemnts
Implicit
param
EventListener type
Defined
yes
EventListenerOuter
In separate java
file
yes
EventListenerInner
In same java file
yes
anonymous
Same method
no
anonymous
inline
ActionListener
TimeTestOuter
ActionListener
TimeTestInner
ActionListener
TimeTestLocal
ActionListener
TimeTestAnon
See inner example
Cross-Cutting Concerns
BlackJack
• Exceptions
• Assertions
• Logging
Shoe
Dealer
Inner and Anonymous Classes
• Though you are captive in the OO paradigm,
you can use inner classes and anonymous
classes to get around this constraint and write
procedural-like code.
• Often times, no one but the enclosing class
cares about an object. In this case, you may
consider using anonymous inner classes.
• Often times, these anon inner classes are both
reference- and type-anonymous.
Anonymous inner classes
Type anonymous : Fight Club - Robert Paulson
https://www.youtube.com/watch?v=GCi_PIz5ek
U
Rules of Fight club
https://www.youtube.com/watch?v=MPITE_Inec
Fight Club Rules of Java
1/ Only concrete classes can be instantiated.
Fight Club Rules of Java
1/ Only concrete classes can be instantiated.
2/ Only concrete classes can be instantiated.
Fight Club Rules of Java
1/ Only concrete classes can be instantiated.
2/ Only concrete classes can be instantiated.
3/ The type of any Object must be of type
Concrete_class. (corollary to 1 and 2)
4/ References may be concrete, abstract, or
interface.
Fight Club Rules of Java
5/ You may create type-anonymous abstractclasses and interfaces by overriding ALL their
contract methods when you declare them.
6/ The “type” of a type-anonymous class is $x
aka Robert Paulson.
Java Event Model
• Used to program behavior in GUIs
• Used extensively in Android.
If a tree falls in a forest and no one is around to hear it, does it make a sound?
Event-Source
(Button)
No Event-Listener
listening
Event
(onClick)
No Catcher
No Event Listener
Event-Source
(Button)
Event-Listener listening
Event
(onClick)
ActionList
ener
Any Object
Catcher ready to catch
Wrong Event
Event source not
registered
Event-Source
(Button)
Event-Listener listening
Event
(Action)
ActionListener
OnMouseListener
Any Object
Event
(Mouse)
Catcher ready to catch
Anonymous inner classes
Type anonymous : Fight Club - Robert Paulson
https://www.youtube.com/watch?v=GCi_PIz5ek
U
$X
Only concrete classes
Rules of Fight club
https://www.youtube.com/watch?v=MPITE_Inec
Model a system
• Object-oriented programming is about
modeling a system.
• Write the problem out as requirements -- this
will essentially be a math world problem (your
favorite kind to solve!)
• Your computer objects map directly to realworld objects (nouns).
• Your methods map directly to real-world
actions (verbs).
Write a very simple application for a contact manager. The the sake of
simplicity, each contact will have a name and a phone number only. The
user should be able to create new contacts and diplay all contacts.
Build a GUI
Write a very simple application for Latin dictionary. The the sake of
simplicity, each entry has a Latin word and an English equivalent, which
could be several words. The user should be able to add a new definition,
delete a definition.
Build a GUI
Describe the system:
The game of BlackJack; a single player plays against the house for money.
His bet is consistently $100.00 and he starts with 1,000.00. There is a shoe
of six 52-card decks which is reshuffled when the shoe is half used. If the
player wins the hand, his gets his bet back plus the amount of the bet. If he
loses, he loses the money, and if he gets blackjack, he get's his bet * 1.5.
The player plays against a dealer who must follow the following strict rules;
aces are worth 11points only, and the dealer must hit on 16 or below. The
player however, is allowed to hit or hold on any hand-value. Furthermore,
aces are worth either 1 or 11, whichever is more advantageous.
An initial two hands are dealt on seperate sides of a table consisting of two
cards apiece. The dealer's hand displays only one card up. The player has
the option to hit, hold, split, double-down, buy insurance, etc. For this
initial version of the game, we'll consider only hit, hold, and deal.
blue are nouns (objects or fields)
red are verbs (methods)
Interfaces
• A class implements an interface rather than
extends it. Any class that implements the
interface must override all the interface
methods with it's own methods.
• Interface names often end with "able" to
imply that they add to the capabilty of the
class.
• An interface is a contract; it defines the
methods
Some fun videos
Reference anonymous - gravity
https://www.youtube.com/watch?v=vKW-Gd_S_xc
Concrete classes: rules of fight club
https://www.youtube.com/watch?v=vJMC_S-DB2I
Type anonymous : Fight Club - Robert Paulson
https://www.youtube.com/watch?v=GCi_PIz5ekU
Dubugger: x-men quicksilver
https://www.youtube.com/watch?v=WGDXO9mlprM
Debugger (lecture 06)
Breakpoints, Bookmarks, TODO
•
•
•
•
•
•
•
•
Alt-2 (see breakpoints and bookmarks)
Cntl-F11 (add bookmark)
//TODO your comment here
Left-click left-margin to add breakpoint
Right-click red-circle to edit
View breakpoints
Conditional breakpoints
All exceptions !(this instanceof
java.lang.ClassNotFoundException)
Stepping through code
•
•
•
•
F8 step-over (used most frequently)
F7 step-into
Shift-F8 step-out
If you want to continue execution until the
next breakpoint is reached or end of execution
is reached. Press PLAY
Watching and evaluating
• Variables: usually provides enough data
• Notice that changing data is blue when you
step
• You can right-click any primitive or object and
“add to watches”
• Right-click to “evaluate expression”
JUNIT
Need to add junit-4.xx.jar and hamcrest-core1.1.jar and add as library to project
Get the following plugin: generateTestCases
Ctrl-Shift-A “download” Downloads...
Browse repositories
Get GenerateTestCases plugin
How to use the Form Designer in IntelliJ
best video on Form Designer in Intellij (in German,
genießen)
https://www.youtube.com/watch?v=0I_1HYMUQrg
(ok video, no sound, English subtitles)
https://www.youtube.com/watch?v=G4jMzEGMKfg
Public and Private (so far)
Modifier | Class | Package | Subclass | World
————————————+———————+—————————+——————————
+———————
public | ✔ | ✔ | ✔ |
✔
————————————+———————+—————————+——————————
+———————
protected | ✔ | ✔ | ✔ |
✘
————————————+———————+—————————+——————————
+———————
no modifier | ✔ | ✔ | ✘ |
✘
————————————+———————+—————————+——————————
+———————
private | ✔ | ✘ |
✘ |
✘