CS 342 – Visual
Programming
First Semester
(431)
WEEK 1
Dr. Walid Karamti
[Link]@[Link]
1
Course profile
● Overview: Developping a User Interface using
Java packages
● Assessment materials:
○ 1 mid-term exam (week 8) = 20%
○ Lab Exam (Project)= 30%
○ Final Exam = 50%
2
Seek Help
● Please feel free to drop up us an email anytime
● You can also book a meeting if you have an
extremely hard problem
Dr. Walid Karamti
[Link]@[Link]
3
Course Materials
●There is no single recommended text book. The texts that I have
used while preparing the course are:
○ Introduction to java-programming comprehensive 11th-edition (2018). Y.
Daniel Liang
○ Java(tm) in Practice: Design Styles and Idioms for Effective Java 1st Edition,
Nigel Warren
●Copies of all lecture slides will be provided on the Blackboard
4
Course Outline
● Chapter 1: OOP Background with Java (3 weeks)
● Chapter 2: User Interfaces using JSwing (5 weeks)
● Chapter 3: In/Out in Java (2 Weeks)
● Chapter 4: Data Bases (1 Week)
● Chapter 5: Threads (2 Weeks)
● Projects presentation: Week 14
5
Outline: Chapter 0- Background about OOP
● Classes and Objects
● Inheritance
● Polymorphism
● Packages
● Abstract classes and Interfaces
● Exceptions
6
Motivations
Suppose you want to develop a graphical user interface as shown
below.
How do you program it?
7
Classes and Objects
Object-oriented programming (OOP) involves programming using Classes
and Objects.
• A class is used to describe something in the world, such as
occurrences, things, external entities, roles, organization
units, places or structures.
A class describes the structure and behavior of a set of similar objects.
It is often described as a template, generalized description, pattern
or blueprint for an object, as opposed to the actual object, itself.
8
Classes and Objects
Once a class of items is defined, a specific instance of the class can be
defined. An instance is also called “object”.
An object has a unique identity, state, and behaviors.
The state of an object consists of a set of data fields
(also known as properties) with their current values.
The behavior of an object is defined by a set of methods, in other words
what the object does.
In other words an object is a software bundle of variables and related
methods.
9
Classes and Objects
A class diagram is simply a rectangle divided into three compartments.
• The topmost compartment contains the name of the class.
• The middle compartment contains a list of attributes (member
variables),
• the bottom compartment contains a list of operations (member
functions).
The purpose of a class diagram is to show the classes within a model.
10
Classes and Objects
11
Classes and Objects
Template for Class Definition
12
Classes and Objects
Template for Class Definition: Example
13
Classes and Objects
Object Declaration
14
Classes and Objects
Object Creation
15
Classes and Objects
Declaration Vs Creation
16
Classes and Objects
Accessing members of a class
. (dot) operator is used to access public members of a class
A general syntax to access public members of a class is as follows
// s is object of Student class Student
s= new Student();
• Referencing the object’s data:
[Link]
e.g., [Link]=“Ali”; // accessing public data member
• Invoking the object’s method:
[Link](arguments) e.g.,
[Link](“Ahmad”); // accessing method
[Link](); // accessing method
17
Classes and Objects
Accessing members of a class
. (dot) operator is used to access public members of a class
A general syntax to access public members of a class is as follows
// s is object of Student class Student
s= new Student();
• Referencing the object’s data:
[Link]
e.g., [Link]=“Ali”; // accessing public data member
• Invoking the object’s method:
[Link](arguments) e.g.,
[Link](“Ahmad”); // accessing method
[Link](); // accessing method
18
Classes and Objects
Exercise
● Objectives
○ Creating Classes
○ Creating Objects via different Types of Constructors
○ Apply the visibilities Rules
○ Testing the “==“ operator
○ Example of Destruction: automatic Garbage Collector
19
Classes and Objects
Exercise 1
20
Classes and Objects
Exercise 1
21
Classes and Objects
Exercise 2
22
Classes and Objects
Exercise 2
23
Inheritance
24
Inheritance: Syntax
25
Inheritance: super Keyword
26
Inheritance: the class Object
27
Inheritance: the class Object
28
Inheritance: the class Object
29
Inheritance: comparing objects
30
Inheritance: Casting references
31
Inheritance: The instanceOf keyword
32
Polymorphism
33
Polymorphism
You can use the object's extra functionality by casting.
Employee ed = new Lawyer();
[Link](); // ok
[Link](); // compiler error
((Lawyer) ed).sue(); // ok
You can't cast an object into something that it is not.
Object otto = new Secretary();
[Link]([Link]()); // ok
[Link](); // compiler error
((Employee) otto).getVacationDays(); // ok
((Lawyer) otto).sue(); // runtime error
34
Polymorphism: Mystery
35
Polymorphism: Mystery
36
Polymorphism: Mystery
Technique 1: diagram
37
Polymorphism: Mystery
Technique 2: Table
38
Polymorphism: Mystery
Snow var3 = new Rain();
var3.method2(); // What's the output?
If the problem does not have any casting, then:
1. Look at the variable's type.
If that type does not have the method: ERROR.
2. Execute the method, behaving like the object's type.
(The variable type no longer matters in this step.)
39
Polymorphism: Example 1
What is the output of the following call?
Snow var1 = new Sleet();
var1.method2();
Answer:
Sleet 2
Snow 2
Sleet 3
40
Polymorphism: Example 2
What is the output of the following call?
Snow var2 = new Rain();
var2.method1();
Answer:
ERROR
(because Snow does not
have a method1)
41
Polymorphism: problem with cast
Snow var2 = new Rain();
((Sleet) var2).method2(); // What's the output?
If the problem does have a type cast, then:
1. Look at the cast type.
If that type does not have the method: ERROR.
2. Make sure the object's type is the cast type or is a subclass of the
cast type. If not: ERROR. (No sideways casts!)
3. Execute the method, behaving like the object's type.
(The variable / cast types no longer matter in this step.)
42
Polymorphism: Example 3
What is the output of the following call?
Snow var2 = new Rain();
((Rain) var2).method1();
Answer:
Rain 1
43
Polymorphism: Example 4
What is the output of the following call?
Snow var2 = new Rain();
((Sleet) var2).method2();
Answer:
ERROR
(because the object's
type, Rain, cannot
be cast into Sleet)
44
Packages
45
Packages
46
Packages
47
Packages
48
Packages: The protected modifier
• The protected modifier can be applied on data and methods in a class.
A protected data or a protected method in a public class can be
accessed by any class in the same package or its subclasses, even if
the subclasses are in a different package.
• private, friendly (default), protected, public
49
Packages: Visibility Modifiers
50
Packages: Visibility Modifiers
51
Packages: the final and abstract Modifiers
52
Packages: the final and abstract Modifiers
53
Packages: the final and abstract Modifiers
54
Packages: the final and abstract Modifiers
55
Packages: the final and abstract Modifiers
56
Packages: the final and abstract Modifiers
57
Abstract class: Polymorphism
58
Interfaces
59
Interfaces
60
Interfaces
61
Interfaces
62
Exceptions: Motivations
When a program runs into a runtime error, the program
terminates abnormally. How can you handle the runtime error
so that the program can continue to run or terminate
gracefully? This is the subject we will introduce in this chapter.
63
Exceptions: Handling Overview
Show runtime error
Quotient Run
Fix it using an if statement
QuotientWithIf Run
With a method
QuotientWithMethod Run
64
Exceptions: Advantages
QuotientWithException Run
Now you see the advantages of using exception handling. It
enables a method to throw an exception to its caller. Without this
capability, a method must handle the exception or terminate the
program.
65
Exceptions: Handling InputMismatchException
InputMismatchExceptionDem Run
o
By handling InputMismatchException, your program will
continuously read an input until it is correct.
66
Exceptions: Types
ClassNotFoundException
ArithmeticException
IOException
Exception NullPointerException
RuntimeException
IndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException
Many more classes
LinkageError
Error VirtualMachineError
Many more classes
67
Exceptions: System Errors
ClassNotFoundException
ArithmeticException
IOException
Exception NullPointerException
RuntimeException
IndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException
Many more classes
System errors are thrown by
JVM and represented in the Error LinkageError
class. The Error class describes
internal system errors. Such Error VirtualMachineError
errors rarely occur. If one does,
there is little you can do beyond Many more classes
notifying the user and trying to
terminate the program gracefully.
68
Exceptions: Pre-defined Exceptions
Exception describes errors
caused by your program ClassNotFoundException
and external ArithmeticException
circumstances. These IOException
errors can be caught and Exception NullPointerException
handled by your program.
RuntimeException
IndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException
Many more classes
LinkageError
Error VirtualMachineError
Many more classes
69
Exceptions: Runtime Exceptions
ClassNotFoundException
ArithmeticException
IOException
Exception NullPointerException
RuntimeException
IndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException
Many more classes
LinkageError
RuntimeException is caused by
programming errors, such as bad
Error VirtualMachineError
casting, accessing an out-of-
bounds array, and numeric errors.
Many more classes
70
Exceptions: Checked Exceptions vs. Unchecked Exceptions
RuntimeException, Error and their subclasses are known as
unchecked exceptions. All other exceptions are known as checked
exceptions, meaning that the compiler forces the programmer to
check and deal with the exceptions.
71
Exceptions: Unchecked Exceptions
In most cases, unchecked exceptions reflect programming logic
errors that are not recoverable. For example, a NullPointerException
is thrown if you access an object through a reference variable
before an object is assigned to it; an IndexOutOfBoundsException is
thrown if you access an element in an array outside the bounds of
the array. These are the logic errors that should be corrected in the
program. Unchecked exceptions can occur anywhere in the
program. To avoid cumbersome overuse of try-catch blocks, Java
does not mandate you to write code to catch unchecked exceptions. 72
Exceptions: Unchecked Exceptions
ClassNotFoundException
ArithmeticException
IOException
Exception NullPointerException
RuntimeException
IndexOutOfBoundsException
Many more classes
Object Throwable IllegalArgumentException
Many more classes
LinkageError
Error VirtualMachineError Unchecked
exception.
Many more classes
73
Exceptions: Declaring, Throwing, and Catching Exceptions
method1() { declare exception
method2() throws Exception {
try {
invoke method2; if (an error occurs) {
}
catch exception catch (Exception ex) { throw new Exception(); throw exception
Process exception; }
} }
}
74
Exceptions: Declaring Exceptions
Every method must state the types of checked
exceptions it might throw. This is known as
declaring exceptions.
public void myMethod()
throws IOException
public void myMethod()
throws IOException, OtherException
75
Exceptions: Throwing Exceptions
When the program detects an error, the program
can create an instance of an appropriate exception
type and throw it. This is known as throwing an
exception. Here is an example,
throw new TheException();
TheException ex = new TheException();
throw ex;
76
Exceptions: Throwing Exceptions Example
/** Set a new radius */
public void setRadius(double newRadius)
throws IllegalArgumentException {
if (newRadius >= 0)
radius = newRadius;
else
throw new IllegalArgumentException(
"Radius cannot be negative");
}
77
Exceptions: Catching Exceptions
try {
statements; // Statements that may throw exceptions
}
catch (Exception1 exVar1) {
handler for exception1;
}
catch (Exception2 exVar2) {
handler for exception2;
}
...
catch (ExceptionN exVar3) {
handler for exceptionN;
}
78
Exceptions: Catching Exceptions
main method { method1 { method2 { An exception
... ... ... is thrown in
try { try { try { method3
... ... ...
invoke method1; invoke method2; invoke method3;
statement1; statement3; statement5;
} } }
catch (Exception1 ex1) { catch (Exception2 ex2) { catch (Exception3 ex3) {
Process ex1; Process ex2; Process ex3;
} } }
statement2; statement4; statement6;
} } }
Call Stack
method3
method2 method2
method1 method1 method1
main method main method main method main method
79
Exceptions: Catch or Declare Checked Exceptions
Suppose p2 is defined as follows:
void p2() throws IOException {
if (a file does not exist) {
throw new IOException("File does not exist");
}
...
}
80
Exceptions: Catch or Declare Checked Exceptions
Java forces you to deal with checked exceptions. If a method declares a
checked exception (i.e., an exception other than Error or
RuntimeException), you must invoke it in a try-catch block or declare to
throw the exception in the calling method. For example, suppose that
method p1 invokes method p2 and p2 may throw a checked exception
(e.g., IOException), you have to write the code as shown in (a) or (b).
void p1() { void p1() throws IOException {
try {
p2(); p2();
}
catch (IOException ex) { }
...
}
}
(a) (b) 81
Exceptions: Catch or Declare Checked Exceptions
Objective: This example demonstrates declaring,
throwing, and catching exceptions by modifying
the setRadius method in the Circle class defined in
Chapter 9. The new setRadius method throws an
exception if radius is negative.
CircleWithException
TestCircleWithException Run
82
Exceptions: Rethrowing Exceptions
try {
statements;
}
catch(TheException ex) {
perform operations before exits;
throw ex;
}
83
Exceptions: The finally Clause
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
84
Exceptions: Trace a Program Execution
Suppose no
exceptions in the
statements
try {
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
85
Exceptions: Trace a Program Execution
The final block is
try { always executed
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
86
Exceptions: Trace a Program Execution
Next statement in
try { the method is
executed
statements;
}
catch(TheException ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
87
Exceptions: Trace a Program Execution
try { Suppose an exception
statement1; of type Exception1 is
statement2; thrown in statement2
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
88
Exceptions: Trace a Program Execution
try { The exception is
statement1; handled.
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
89
Exceptions: Trace a Program Execution
try { The final block is
statement1; always executed.
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
90
Exceptions: Trace a Program Execution
try { The next statement in
statement1; the method is now
statement2; executed.
statement3;
}
catch(Exception1 ex) {
handling ex;
}
finally {
finalStatements;
}
Next statement;
91
Exceptions: Trace a Program Execution
try {
statement1; statement2 throws an
statement2; exception of type
statement3;
}
Exception2.
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Next statement;
92
Exceptions: Trace a Program Execution
try {
statement1; Handling exception
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Next statement;
93
Exceptions: Trace a Program Execution
try {
statement1; Execute the final block
statement2;
statement3;
}
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Next statement;
94
Exceptions: Trace a Program Execution
try {
statement1; Rethrow the exception
statement2; and control is
statement3;
}
transferred to the caller
catch(Exception1 ex) {
handling ex;
}
catch(Exception2 ex) {
handling ex;
throw ex;
}
finally {
finalStatements;
}
Next statement;
95
Exceptions: Cautions When Using Exceptions
● Exception handling separates error-handling code from
normal programming tasks, thus making programs easier
to read and to modify. Be aware, however, that exception
handling usually requires more time and resources
because it requires instantiating a new exception object,
rolling back the call stack, and propagating the errors to
the calling methods.
96
Exceptions: When to Use Exceptions
When should you use the try-catch block in the code? You should use
it to deal with unexpected error conditions. Do not use it to deal with
simple, expected situations. For example, the following code
try {
[Link]([Link]());
}
catch (NullPointerException ex) {
[Link]("refVar is null");
}
97
Exceptions: When to Use Exceptions
is better to be replaced by
if (refVar != null)
[Link]([Link]());
else
[Link]("refVar is null");
98
Exceptions: Defining Custom Exception Classes
• Use the exception classes in the API whenever possible.
• Define custom exception classes if the predefined classes
are not sufficient.
• Define custom exception classes by extending Exception or
a subclass of Exception.
99
Exceptions: Custom Exception Class Example
In Listing 13.8, the setRadius method throws an exception if the
radius is negative. Suppose you wish to pass the radius to the
handler, you have to create a custom exception class.
InvalidRadiusException
CircleWithRadiusException
TestCircleWithRadiusException Run
100