Download presentation
Presentation is loading. Please wait.
1
Agenda Lec05 Exceptions API
Reference- and Type-Anonymity Swing Review
2
Aperture and underlying object
Review: Aperture and underlying object
3
Object S Number C Double
5
A reference is an aperture.
6
A reference is an aperture.
Object obj = new Double(5.87); reference Object Double Underlying object
7
A reference is an aperture.
Number num = new Double(89.17); Number reference Double Underlying object
8
A reference is an aperture.
Double dub = new Double(72.17); reference Double Double Underlying object
9
A reference is an aperture.
Comparable com = new Double(72.17); reference C Double Underlying object
10
Once instantiated on the heap, that object's type can NEVER change.
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
11
Exceptions: Checked versus Unchecked Exceptions
12
Probable Source Example of Error: System-out-of-memory Error
Within your control Probable Source Checked User should Recover Error NO JVM RuntimeException (unchecked) YES Programmer All other exceptions (checked) User, External resources, Thread Example of Error: System-out-of-memory Error Examples of RuntimeException: ClassCastException, NumberFormatException. Example of checked Exceptions: EOFExcception,
13
Your program running in JVM Hosting system Green = unchecked
Orange are checked exceptions and yellow are unchecked exceptions Hosting system Green = unchecked Blue = checked 13
14
Orange are checked exceptions and yellow are unchecked exceptions
14
16
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.
17
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
18
exception is thrown up. It may be caught (intercepted)
exception is thrown up. It may be caught (intercepted). As it passes through each layer of the call stack, you have an opportunity to intercept it. If you don't, it'll propogate all the way up to the VM and boom. See debug dir examples 18
19
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.
20
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?
21
Checked versus 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.
22
Checked versus Unchecked
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 green-zone are recoverable from the chaos of the exterior environment.
23
The debate over checked and unchecked
See: 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
24
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.
25
Source Code Online
26
Source Code Online Please avail yourselves of the many excellent sources for source code, both full applications and snippets. (best for snippets) GitHub.com BitBucket.org (best for full apps) 26
27
Guidelines for using found source code
If you know the URL where you got it, cite like so: // -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.
28
Reflection
29
Reflection Very useful when first learning an OO language.
Reference anonymous - gravity
30
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
31
Reflection Name of Driver implemnts Implicit param EventListener type
Defined TimeTestOuter ActionListener yes EventListenerOuter In separate java file TimeTestInner EventListenerInner In same java file TimeTestLocal anonymous Same method TimeTestAnon no inline See inner example
32
Cross-Cutting Concerns
BlackJack Shoe Dealer Exceptions Assertions Logging it makes sense to have a model for these that are independent of any class. 32
33
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.
34
Anonymous inner classes
Type anonymous : Fight Club - Robert Paulson U Rules of Fight club c
35
Fight Club Rules of Java
1/ Only concrete classes can be instantiated.
36
Fight Club Rules of Java
1/ Only concrete classes can be instantiated. 2/ Only concrete classes can be instantiated.
37
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.
38
Fight Club Rules of Java
5/ You may create type-anonymous abstract- classes 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.
39
Java Event Model Used to program behavior in GUIs
Used extensively in Android.
40
Yes, sound is a natural phenomena. But in Java, the answer is no.
If a tree falls in a forest and no one is around to hear it, does it make a sound? 40
41
Step 1a/ Create a concrete Listener class that implements the Particular listener interface.
Step 1b/ or Let the enclosing Activity implement Listener interface and override the methods from the Interface Step 2/ register the event-source with the event-listener Step 3/ Define the behavior 41
42
No Event Listener Event-Source (Button) No Event-Listener listening
(onClick) No Catcher The event often encapsulates data about that event, the coordinates where you clicked, the time you clicked, the user_name, etc. If no one is around to listen, it's just ignored. The event source could be any number of GUI elements. No Event Listener 42
43
Event-Listener listening ActionListener Event-Source (Button)
(onClick) Any Object Catcher ready to catch The catcher is registered to listen to events from all the players on his team. If a player throws his bat into the dugout, the catcher will not try to catch it. If someone in the stands throws a soccer ball into the field, the catcher will not catch it. Conditions the catcher will catch the event: 1/ The event source (thrower) is registered by the catcher 2/ it's the correct event (ball) The event encapsulates data about that event, the coordinates where you clicked, the time you clicked, the user_name, etc. If no one is around to listen, it's just ignored. In Android, the events contain data, but since it's a resource-constrained environment, not as much as Java. In most cases, it's a good idea to leave the controller methods inside the enclosing activity as anonymous inner-classes or just implment approriate methods and call "this". The catcher can catch the event and take appropriate action (if runner stealing second, then throw ball to second-base) Method called catchBall(Player ply){ if (ply == pitcher){ catch the ball and throw it back if (ply == third-baseman) tag the runner stealing home } 43
44
Wrong event. The catcher is a baseball-throw-event-listener
Wrong event. The catcher is a baseball-throw-event-listener. If you throw a football at the baseball catcher, it's going to sail over his head. Wrong Event 44
45
Event source not registered
46
Event-Listener listening Event-Source (Button)
Action-Listener OnMouse-Listener Event-Listener listening Event-Source (Button) Event (Action) Any Object Event (Mouse) Catcher ready to catch The catcher is registered to listen to events from all the players on his team. If a player throws his bat into the dugout, the catcher will not try to catch it. If someone in the stands throws a soccer ball into the field, the catcher will not catch it. Conditions the catcher will catch the event: 1/ The event source (thrower) is registered by the catcher 2/ it's the correct event (ball) The event encapsulates data about that event, the coordinates where you clicked, the time you clicked, the user_name, etc. If no one is around to listen, it's just ignored. In Android, the events contain data, but since it's a resource-constrained environment, not as much as Java. In most cases, it's a good idea to leave the controller methods inside the enclosing activity as anonymous inner-classes or just implment approriate methods and call "this". The catcher can catch the event and take appropriate action (if runner stealing second, then throw ball to second-base) Method called catchBall(Player ply){ if (ply == pitcher){ catch the ball and throw it back if (ply == third-baseman) tag the runner stealing home } 46
47
Anonymous inner classes
Type anonymous : Fight Club - Robert Paulson U $X
48
Only concrete classes Rules of Fight club
49
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 real- world objects (nouns). Your methods map directly to real-world actions (verbs).
50
Write a very simple application for a contact manager
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 Solve a simple word problem. Red are verbs and blue are nouns. Model the system! Nouns are either objects or fields (properties of objects). Verbs are methods. 50
51
Write a very simple application for Latin dictionary
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 Solve a simple word problem. Red are verbs and blue are nouns. Model the system! Nouns are either objects or fields (properties of objects). Verbs are methods. 51
52
blue are nouns (objects or fields) red are verbs (methods)
Describe the system: The game of BlackJack; a single player plays against the house for money. His bet is consistently $ and he starts with 1, 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) Solve a simple word problem. Red are verbs and blue are nouns. Model the system! Nouns are either objects or fields (properties of objects). Verbs are methods. 52
53
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
54
Some fun videos Reference anonymous - gravity Concrete classes: rules of fight club Type anonymous : Fight Club - Robert Paulson Dubugger: x-men quicksilver
55
Debugger (lecture 06)
56
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)
57
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
58
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”
59
JUNIT Need to add junit-4.xx.jar and hamcrest-core- 1.1.jar and add as library to project Get the following plugin: generateTestCases Ctrl-Shift-A “download” Downloads... Browse repositories Get GenerateTestCases plugin
60
How to use the Form Designer in IntelliJ
best video on Form Designer in Intellij (in German, genießen) (ok video, no sound, English subtitles)
61
Public and Private (so far)
Modifier | Class | Package | Subclass | World ————————————+———————+—————————+——————————+——————— public | ✔ | ✔ | ✔ | ✔ protected | ✔ | ✔ | ✔ | ✘ no modifier | ✔ | ✔ | ✘ | ✘ private | ✔ | ✘ | ✘ | ✘
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.