Académique Documents
Professionnel Documents
Culture Documents
1-1
Introduction
Objectives
This lesson covers the following objectives:
Examine the course sections
State the goal of the course
Become familiar with Oracle iLearning
Explain the course map
Describe the software used in this course
Recognize the IDEs used in this course
JF 1-1
Introduction
Section 0:
Resources
Section 5:
Program Structure
Section 1:
Introduction
Section 6:
Arrays and Exceptions
Section 2:
Alice 3
Section 3:
Greenfoot
Midterm
Exam
JF 1-1
Introduction
Section 7:
Java Classes
Final
Exam
Course Goal
You will learn the basic elements of computer programming
and the Java programming language to start writing your own
Java programs.
By the end of this course you should be able to:
Create animations and games.
Demonstrate your knowledge of Java technology and the Java
programming language.
Use the Java programming language to create applications.
Integrate decision, looping, and other intermediate code to create
applications.
JF 1-1
Introduction
Oracle iLearning
Oracle iLearning is a learning management system used for
this course.
Your instructor will provide you with an Oracle iLearning
username and password.
You will use iLearning to access:
Curriculum
Quizzes
Exams
JF 1-1
Introduction
Student Guides PDF slides with additional notes for each lesson
Practice Guides PDF document with practice activities
Project Guides* PDF document with project activities
Quizzes Online quiz for each lesson
Exams Online midterm and final exam for each course
Additional Resources Some lessons include additional materials as
needed
JF 1-1
Introduction
Course Map
The course map is located in Section 0 of the course
It is a lesson planning tool used to plan how you will complete
lessons in the amount of time you have available over a unit
or semester.
Lessons are designed in a modular way.
The course map provides a recommended duration of each
lesson.
The map is based upon 45 minute class duration, but can be
adapted to shorter or longer class timings.
JF 1-1
Introduction
Software
In this course you will use the following software:
JF 1-1
Introduction
JF 1-1
Introduction
10
Terminology
Key terms used in this lesson included:
Oracle iLearning
IDE
JF 1-1
Introduction
11
Summary
In this lesson, you should have learned how to:
State the goal of the course
Explain the course map
Describe the teaching format used in class
Become familiar with Oracle iLearning
Recognize the IDEs used in this course
JF 1-1
Introduction
12
Java Fundamentals
2-1
Getting Started with Alice 3
Objectives
This lesson covers the following objectives:
Identify scene components
Create and save a new project
Add an object to a scene
Communicate the value of saving multiple versions of a scene
Code a simple programming instruction
Use the copy and undo command
Understand the value of testing and debugging
JFS2L1
Getting Started with Alice 3
Initial Scene
An initial scene is the starting point of your animation. It has
three components:
A background template which provides the sky, ground, and light.
Non-moving scenery objects which provide the setting.
Moving objects which provide the action.
The initial scene is the first scene of an animation where you select
the background template and position the objects.
JFS2L1
Getting Started with Alice 3
Room is a
template.
Bipeds are
acting objects.
JFS2L1
Getting Started with Alice 3
JFS2L1
Getting Started with Alice 3
JFS2L1
Getting Started with Alice 3
JFS2L1
Getting Started with Alice 3
JFS2L1
Getting Started with Alice 3
JFS2L1
Getting Started with Alice 3
10
JFS2L1
Getting Started with Alice 3
11
JFS2L1
Getting Started with Alice 3
12
JFS2L1
Getting Started with Alice 3
13
Scene Editor
In the Scene editor, you can:
JFS2L1
Getting Started with Alice 3
14
JFS2L1
Getting Started with Alice 3
15
Gallery
The gallery is a collection of three-dimensional objects that
you can insert into the scene.
The gallery is organized using tabs.
To find objects, browse the gallery tabs or use the Search
Gallery feature to search by keyword.
Breadcrumb menus display as you select classes.
JFS2L1
Getting Started with Alice 3
16
Gallery Tabs
The gallery has six tabs:
Tab
Function
Search Gallery
Shapes/Text
My Classes
17
Select a Class
The Class Hierarchy tab groups objects by mobility type
(biped, flyer, etc.).
A class contains the instructions that define the appearance and
movement of an object. All objects within a class have common
properties. The class provides instructions to Alice 3 for creating and
displaying the object when it is added to your scene.
JFS2L1
Getting Started with Alice 3
18
Class Example
Classes can contain sub-classes. Consider the example below.
The Alice class is a sub-class of the Biped class. There are two
Alice sub-classes in the gallery.
Every Alice added to a scene inherits the properties that all
Biped objects have in common: two legs, moveable joints etc.
JFS2L1
Getting Started with Alice 3
19
JFS2L1
Getting Started with Alice 3
20
JFS2L1
Getting Started with Alice 3
21
Code Editor
Click the Edit Code button to display the Code editor. The
Code editor is where you add the programming instructions
to program your animation.
JFS2L1
Getting Started with Alice 3
22
Methods Panel
The Procedures tab, located within the Methods Panel in the
Code editor, displays pre-defined methods for the selected
instance, as well as methods defined for the class of objects.
A procedure is a piece of program
code that defines how the object
should execute a task. Alice 3 has a
set of procedures for each class;
however, users can create or
"declare" new procedures.
JFS2L1
Getting Started with Alice 3
23
JFS2L1
Getting Started with Alice 3
24
JFS2L1
Getting Started with Alice 3
25
JFS2L1
Getting Started with Alice 3
26
Direction
Amount
Duration
Text
JFS2L1
Getting Started with Alice 3
27
JFS2L1
Getting Started with Alice 3
28
JFS2L1
Getting Started with Alice 3
29
JFS2L1
Getting Started with Alice 3
30
JFS2L1
Getting Started with Alice 3
31
Undo an Action
Undo an action using the Undo option on the Edit menu, or
the keyboard shortcut CTRL + Z.
JFS2L1
Getting Started with Alice 3
32
JFS2L1
Getting Started with Alice 3
33
JFS2L1
Getting Started with Alice 3
34
JFS2L1
Getting Started with Alice 3
35
JFS2L1
Getting Started with Alice 3
36
Terminology
Key terms used in this lesson included:
Argument
Bug
Class
Code editor
Debugging
Gallery
JFS2L1
Getting Started with Alice 3
37
Terminology
Key terms used in this lesson included:
Initial scene
Instance
Procedure
Scene editor
Template
JFS2L1
Getting Started with Alice 3
38
Summary
In this lesson, you should have learned how to:
Identify scene components
Create and save a new project
Add an object to a scene
Communicate the value of saving multiple versions of a scene
Code a simple programming instruction
Use the copy and undo commands
Understand the value of testing and debugging
JFS2L1
Getting Started with Alice 3
39
Java Fundamentals
2-2
Add and Position Objects
Objectives
This lesson covers the following objectives:
Open a saved version of a project
Add multiple objects to a scene
Describe the difference between precise positioning and
drag-and-drop (or imprecise) positioning
Use a one-shot procedure to precisely position an object in a
scene
JF 2-2
Add and Position Objects
Objectives
This lesson covers the following objectives:
Edit properties of an object in the Scene editor
Describe three-dimensional positioning axes
Position the sub-parts of an object in the Scene editor
JF 2-2
Add and Position Objects
JF 2-2
Add and Position Objects
JF 2-2
Add and Position Objects
JF 2-2
Add and Position Objects
JF 2-2
Add and Position Objects
JF 2-2
Add and Position Objects
Orientation of Objects
Objects and their sub-parts move relative to their own
orientation, or sense of direction.
An object that is facing toward the back of the scene,
programmed to move forward 2 meters, moves 2 meters
further toward the back of the scene.
JF 2-2
Add and Position Objects
10
JF 2-2
Add and Position Objects
11
JF 2-2
Add and Position Objects
12
JF 2-2
Add and Position Objects
13
JF 2-2
Add and Position Objects
14
JF 2-2
Add and Position Objects
15
JF 2-2
Add and Position Objects
16
JF 2-2
Add and Position Objects
17
JF 2-2
Add and Position Objects
18
JF 2-2
Add and Position Objects
19
JF 2-2
Add and Position Objects
20
Description
Default
Rotation
Translation
Resize
Note: If you select a very large object in the scene, and then
select the Resize handle, the positioning arrow that helps you
resize the object may appear off of the screen. If this
happens, select the Resize handle and then use the scrolling
button on your mouse to resize the object.
JF 2-2
Add and Position Objects
21
JF 2-2
Add and Position Objects
22
Modifying Properties
Properties can be modified during scene setup and during
animation execution. For example:
Change the Opacity property of an instance to 0 during scene setup to
make it disappear.
Create a programming statement to set the Opacity property of the
instance to 1 so the instance reappears in the scene during execution
of the animation.
JF 2-2
Add and Position Objects
23
JF 2-2
Add and Position Objects
24
JF 2-2
Add and Position Objects
25
JF 2-2
Add and Position Objects
26
JF 2-2
Add and Position Objects
27
Terminology
Key terms used in this lesson included:
Orientation
One-shot procedure
Procedure
Properties
JF 2-2
Add and Position Objects
28
Summary
In this lesson, you should have learned how to:
Open a saved version of a project
Add multiple objects to a scene
Describe the difference between precise positioning and
drag-and-drop (or imprecise) positioning
Use a one-shot procedure to precisely position an object in a
scene
JF 2-2
Add and Position Objects
29
Summary
In this lesson, you should have learned how to:
Edit properties of an object in the Scene editor
Describe three-dimensional positioning axes
Position the sub-parts of an object in the Scene editor
JF 2-2
Add and Position Objects
30
Java Fundamentals
2-3
Procedures and Arguments
Objectives
This lesson covers the following objectives:
Toggle between, and describe the visual differences between,
the Scene editor and the Code editor
Locate and describe the purpose of the methods panel and
the procedures tab
Use procedures to move objects
Add Java programming procedures to the Code editor
JF 2-3
Procedures and Arguments
Objectives
This lesson covers the following objectives:
Demonstrate how procedure values can be altered
Create programming comments
Reorder, edit, delete, copy, and disable programming
statements
Test and debug an animation
JF 2-3
Procedures and Arguments
JF 2-3
Procedures and Arguments
Select Instance
First, select the instance that
you want to program.
This ensures that you are
creating a programming
instruction for the correct
instance.
Select an instance by clicking
on the instance in the small
scene window or by using
the instance pull down menu
below the small scene
window.
JF 2-3
Procedures and Arguments
Methods Panel
The Methods Panel
contains two tabs:
Procedures: All pre-defined
procedures for an object.
Functions: All pre-defined
functions for an object.
JF 2-3
Procedures and Arguments
Procedures Tab
The Procedures tab displays pre-defined procedures for the
selected instance, as well as procedures of your own that you
define.
A procedure is a piece of program
code that defines how the object
should execute a task. Alice 3 has a
set of procedures for each class;
however, users can create
("declare") new procedures.
JF 2-3
Procedures and Arguments
Functions Tab
The Functions tab displays pre-defined functions for the
selected instance, as well as functions of your own that you
define.
A Function computes and answers a
question about an object, such as,
"What is its width or height?", or
"What is its distance from another
object?" Alice 3 has a set of
functions for each class; however,
users can declare new functions.
JF 2-3
Procedures and Arguments
JF 2-3
Procedures and Arguments
10
Control Statements
At the bottom of the myFirstMethod tab you will find the
Alice 3 control statements.
JF 2-3
Procedures and Arguments
11
Object Movement
Object movement is egocentric:
Objects move based on the direction they face.
Up
Down
Forward
Backward
Right
Left
JF 2-3
Procedures and Arguments
12
Description
Move
Move Toward
Move To
Delay
Say
JF 2-3
Procedures and Arguments
13
Description
Turn
Roll
JF 2-3
Procedures and Arguments
14
JF 2-3
Procedures and Arguments
15
JF 2-3
Procedures and Arguments
16
JF 2-3
Procedures and Arguments
17
Arguments
Arguments are selected
after the procedure is
dropped onto the Code
editor.
Argument types may
include:
Object
Direction
Direction amount
Time duration
Text
JF 2-3
Procedures and Arguments
18
Argument Menu
The argument menu offers default argument values to select
from. If none of the defaults are suitable, select the Custom
DecimalNumber option so that you can specify a more
accurate argument value.
JF 2-3
Procedures and Arguments
19
JF 2-3
Procedures and Arguments
20
Arguments as Placeholders
When a procedure is dropped into the Code editor, all
argument values must be specified.
There will be times that you select an argument value as a
temporary placeholder value that will be replaced later.
For example, you may want an object to move forward but
you are not sure how far.
Select a placeholder value of 2 meters, run the animation,
determine that a different value is needed, and then edit the
value.
You can also specify a placeholder value that you will replace
later with a function or a variable.
JF 2-3
Procedures and Arguments
21
22
JF 2-3
Procedures and Arguments
23
JF 2-3
Procedures and Arguments
24
JF 2-3
Procedures and Arguments
25
JF 2-3
Procedures and Arguments
26
27
JF 2-3
Procedures and Arguments
28
JF 2-3
Procedures and Arguments
29
JF 2-3
Procedures and Arguments
30
Programming Comments
Including programming comments in an animation helps
humans understand the flow of the programming.
Comments:
Describe the intention of the programming instructions.
Do not affect the functionality of the program because they are ignored
during its execution.
Are typically placed above the block of programming statements that it
describes.
Are often written first, in large programs, as an outline of the
programming instructions.
JF 2-3
Procedures and Arguments
31
JF 2-3
Procedures and Arguments
32
JF 2-3
Procedures and Arguments
33
Terminology
Key terms used in this lesson included:
Argument
Code editor
Comments
Functions
Methods panel
Orientation
Procedure
JF 2-3
Procedures and Arguments
34
Summary
In this lesson, you should have learned how to:
Toggle between, and describe the visual differences between,
the Scene editor and the Code editor
Locate and describe the purpose of the methods panel and
the procedures tab
Use procedures to move objects
Add Java programming procedures to the Code editor
JF 2-3
Procedures and Arguments
35
Summary
In this lesson, you should have learned how to:
Demonstrate how procedure values can be altered
Create programming comments
Reorder, edit, delete, copy, and disable programming
statements
Test and debug an animation
JF 2-3
Procedures and Arguments
36
Java Fundamentals
2-4
Rotation and Randomization
Objectives
This lesson covers the following objectives:
Correlate storyboard statements with program execution
tasks
Add a control statement to the Code editor
Use random numbers to randomize motion
JF 2-4
Rotation and Randomization
JF 2-4
Rotation and Randomization
Do together
Storyboard Action
Programming Instructions
JF 2-4
Rotation and Randomization
Object Movement
Object movement is egocentric:
Objects move based on the direction they face.
Up
Down
Forward
Backward
Right
Left
JF 2-4
Rotation and Randomization
Description
Turn
Roll
JF 2-4
Rotation and Randomization
10
JF 2-4
Rotation and Randomization
11
12
Sub-Part Rotation
Some objects have moveable sub-parts.
For example, the clock's hands can turn or roll.
Rotation can be applied to an entire object, or select subparts of the object.
An object's sub-part displays rings that show its range of
motion.
JF 2-4
Rotation and Randomization
13
14
Control Statements
Control statements define how programming statements are
executed in the program.
myFirstMethod is created with a default Do in order control
statement. Within it, all programming statements execute
sequentially by default.
Procedure
Description
Do in order
Do together
Count
While
15
16
JF 2-4
Rotation and Randomization
17
JF 2-4
Rotation and Randomization
18
JF 2-4
Rotation and Randomization
19
Random Numbers
Random numbers are numbers generated by the computer
with no predictable pattern to their sequence.
Random numbers are generated within a given range of
numbers.
Computers may require random numbers for:
Security: for example, randomly generated passwords.
Simulation: for example, earth science modeling
(i.e., erosion over time).
JF 2-4
Rotation and Randomization
20
15674
-6934022
0.371
-89.763
JF 2-4
Rotation and Randomization
21
JF 2-4
Rotation and Randomization
22
JF 2-4
Rotation and Randomization
23
JF 2-4
Rotation and Randomization
24
Terminology
Key terms used in this lesson included:
Control statements
Nesting
Random numbers
Textual storyboard
JF 2-4
Rotation and Randomization
25
Summary
In this lesson, you should have learned how to:
Correlate storyboard statements with program execution
tasks
Add a control statement to the Code editor
Use random numbers to randomize motion
JF 2-4
Rotation and Randomization
26
Java Fundamentals
2-5
Declare Procedures
Objectives
This lesson covers the following objectives:
Compare and define an animation and a scenario
Write a storyboard
Flowchart a storyboard
Describe inheritance and how traits are passed from
superclasses to subclasses
JF 2-5
Declare Procedures
Objectives
This lesson covers the following objectives:
Describe when to implement procedural abstraction
Demonstrate how to declare a procedure
Identify and use procedural abstraction techniques to simplify
animation development
JF 2-5
Declare Procedures
Object Movement
Professional animators begin their process by developing a
scenarioor storythat gives the animation a purpose.
Examples:
JF 2-5
Declare Procedures
Scenario
Animation
Story
Lesson
Memorizing chemistry
symbols is difficult.
Process
Game
JF 2-5
Declare Procedures
What is a Storyboard?
A storyboard identifies the design specifications for the
animation scenario:
How objects appear, move, speak, interact, and so on.
JF 2-5
Declare Procedures
Storyboard Formats
Storyboards are created in the following formats:
Drawn with paper and pencil.
Created using digital tools such as a word processing program, paint or
drawing program, or presentation.
Created using comments in the Alice 3 Code editor.
JF 2-5
Declare Procedures
Visual Storyboards
A visual storyboard helps the reader understand:
JF 2-5
Declare Procedures
JF 2-5
Declare Procedures
10
Textual Storyboards
A textual storyboard helps the reader understand the actions
that will take place during the animation.
The moving and non-moving objects can be easily identified
within the action statements, but a more detailed description
may be necessary if additional programmers are also involved
in implementing any scene.
An algorithm is a list of actions to perform a task or solve a problem.
In computing, a textual storyboard is an algorithm.
JF 2-5
Declare Procedures
11
JF 2-5
Declare Procedures
12
JF 2-5
Declare Procedures
13
Definition
Scene
Objects
Moving or non-moving
characters that you program to
move and act.
Actions
User Interactions
Design Specifications
Examples
14
Flowcharting a Storyboard
Flowcharting a storyboard helps you organize the flow of the
animation actions and conditions.
True
Boy leaves
phone on
bench
False
Boy keeps
walking
End
JF 2-5
Declare Procedures
15
JF 2-5
Declare Procedures
16
Inherited Characteristics
Let's examine how a Dalmatian inherits its characteristics:
Characteristics of the Dog class (the parent class or
"superclass") include four legs, two eyes, fur, and the ability
to bark.
Characteristics of the Dalmatian breed class (the child class or
"subclass," which is a subset of the dog class) include white
fur, black spots, and other characteristics.
Dog Class (Superclass)
Dalmatian Class
(Subclass)
JF 2-5
Declare Procedures
17
Class Inheritance
Just like animals in the real world, objects in the programming
world inherit the characteristics of their class, including all of
the class's methods (procedures and functions).
For example, all objects within the quadruped class in Alice
inherit the quadruped characteristics of four legs, a head, a
body, etc.
Within this quadruped superclass, subclasses exist for dogs,
cats, wolves, lions, cows, etc.
Each subclass adds characteristics that more specifically
identify the objects within it.
JF 2-5
Declare Procedures
18
JF 2-5
Declare Procedures
19
Inheritance
When a Dalmatian object is created, it inherits procedures,
functions, and properties from the quadruped class and the
Dalmatian subclass that you can view in the Code editor.
JF 2-5
Declare Procedures
20
JF 2-5
Declare Procedures
21
myFirstMethod Tab
The myFirstMethod tab is displayed by default when the Code
editor is opened.
JF 2-5
Declare Procedures
22
Class Hierarchy
Click the class hierarchy drop-down menu to the left of the
myFirstMethod tab (indicated by a down-pointing arrow) to
view the list of classes and subclasses in your animation.
JF 2-5
Declare Procedures
23
JF 2-5
Declare Procedures
24
Procedural Abstraction
Review the existing code or the textual storyboard to identify
and plan the methods that you need to declare in your
program.
Procedural abstraction may need to be implemented if an
object in Alice needs to perform an action, but there isn't an
inherited procedure that accomplishes that action.
Identify a repetitive behavior and create one method for it:
Simplifies the code, making it easier to read.
Allows many objects of a class to use the same method.
Allows subclasses of a superclass to use the method.
JF 2-5
Declare Procedures
25
JF 2-5
Declare Procedures
26
JF 2-5
Declare Procedures
27
JF 2-5
Declare Procedures
28
JF 2-5
Declare Procedures
29
JF 2-5
Declare Procedures
30
Do together:
Bird flies
Bird moves forward
Do together:
Bird turns right shoulder forward
Bird turns left shoulder forward
Bird moves forward
JF 2-5
Declare Procedures
31
JF 2-5
Declare Procedures
32
JF 2-5
Declare Procedures
33
JF 2-5
Declare Procedures
34
JF 2-5
Declare Procedures
35
36
JF 2-5
Declare Procedures
37
JF 2-5
Declare Procedures
38
JF 2-5
Declare Procedures
39
JF 2-5
Declare Procedures
40
JF 2-5
Declare Procedures
41
JF 2-5
Declare Procedures
42
JF 2-5
Declare Procedures
43
44
Terminology
Key terms used in this lesson included:
Algorithm
Declared procedures
Inheritance
Procedural abstraction
Scenario
Storyboard
JF 2-5
Declare Procedures
45
Summary
In this lesson, you should have learned how to:
Compare and define an animation and a scenario
Write a storyboard
Flowchart a storyboard
Describe inheritance and how traits are passed from
superclasses to subclasses
JF 2-5
Declare Procedures
46
Summary
In this lesson, you should have learned how to:
Describe when to implement procedural abstraction
Demonstrate how to declare a procedure
Identify and use procedural abstraction techniques to simplify
animation development
JF 2-5
Declare Procedures
47
Java Fundamentals
2-6
Control Statements
Objectives
This lesson covers the following objectives:
Define multiple control statements to control animation
timing
Create an animation that uses a control statement to control
animation timing
Recognize programming constructs to invoke simultaneous
movement
JF 2-6
Control Statements
Arguments
The arguments of a procedure may be edited or further
defined to control object movement and timing.
Examples of Alice 3 arguments include:
Object
Direction
Direction amount
Time duration
JF 2-6
Control Statements
Arguments Display
Below are examples of arguments in a procedure.
JF 2-6
Control Statements
JF 2-6
Control Statements
JF 2-6
Control Statements
Simultaneous Movements
To create simultaneous movements for an object, use the Do
together control statement.
Control Statement
Do In Order
Do Together
Description
Default control statement in Code editor.
Executes procedures in sequential order.
Executes procedures simultaneously.
Used for simultaneous movements such as walking
and sitting motions.
JF 2-6
Control Statements
JF 2-6
Control Statements
JF 2-6
Control Statements
10
Programming Instructions
Whole body moves forward
Left shoulder turns right
Right shoulder turns right
Do Together
11
JF 2-6
Control Statements
12
JF 2-6
Control Statements
13
setVehicle Procedure
The setVehicle procedure employs the concept of a rider
object and a vehicle object.
The rider object is selected when the setVehicle procedure is
used to specify the vehicle for the rider.
Then, when the vehicle object is programmed to move, the
rider object will automatically move with it.
Examples:
Person rides a camel or horse.
Camera follows a helicopter to shoot the scene from the helicopter's
point of view.
JF 2-6
Control Statements
14
JF 2-6
Control Statements
15
JF 2-6
Control Statements
16
JF 2-6
Control Statements
17
JF 2-6
Control Statements
18
Terminology
Key terms used in this lesson included:
Arguments
Do together control statement
Do in order control statement
JF 2-6
Control Statements
19
Summary
In this lesson, you should have learned how to:
Define multiple control statements to control animation
timing
Create an animation that uses a control statement to control
animation timing
Recognize programming constructs to invoke simultaneous
movement
JF 2-6
Control Statements
20
Java Fundamentals
2-7
Functions
Objectives
This lesson covers the following objectives:
Using functions to control movement based on a return value
JF 2-7
Functions
Functions
Functions:
Are used to ask questions about properties of an object.
Are similar to procedures except that they return a value of a particular
type.
Can be used to compute a value.
JF 2-7
Functions
JF 2-7
Functions
Functions Tab
The Functions tab is in the methods panel.
Select the object from the Instance menu, and then view its
functions.
JF 2-7
Functions
JF 2-7
Functions
JF 2-7
Functions
JF 2-7
Functions
10
JF 2-7
Functions
11
JF 2-7
Functions
12
Avoid Collisions
You can enhance function calls using the math operators (+)
addition, (-) subtraction, (*) multiplication, and (/) division.
For example, you can reduce the distance an object will move
to avoid a collision.
JF 2-7
Functions
13
Z = X (Y / 2)
Bunny
JF 2-7
Functions
14
Dalmatian
Bunny
JF 2-7
Functions
15
Bunny
JF 2-7
Functions
16
JF 2-7
Functions
17
JF 2-7
Functions
18
JF 2-7
Functions
19
20
Bunny
Dalmatian
Distance from Dalmatian to Bunny
Dalmatian depth
JF 2-7
Functions
21
Bunny
Dalmatian
Distance from Dalmatian to Bunny
Dalmatian depth
JF 2-7
Functions
22
JF 2-7
Functions
23
Terminology
Key terms used in this lesson included:
Functions
Math operators
JF 2-7
Functions
24
Summary
In this lesson, you should have learned how to:
Use functions to control movement based on a return value
JF 2-7
Functions
25
Java Fundamentals
2-8
IF and WHILE Control Structures
Objectives
This lesson covers the following objectives:
Use the IF control structure to effect execution of instructions
Use the WHILE control structure to create a conditional loop
for repetitive behavior
JF 2-8
IF and WHILE Control Structures
Control Structures
Control structures are pre-defined statements that determine
the order in which programming instructions are executed.
You should be familiar with the Do together and Do in order
control structures from previous topics.
JF 2-8
IF and WHILE Control Structures
Do in order
Count
If
For each in
While
Do together
Each in together
JF 2-8
IF and WHILE Control Structures
JF 2-8
IF and WHILE Control Structures
JF 2-8
IF and WHILE Control Structures
JF 2-8
IF and WHILE Control Structures
JF 2-8
IF and WHILE Control Structures
JF 2-8
IF and WHILE Control Structures
10
IF Control Structure
The IF control structure requires a condition of true or false
when the structure is dragged into the program.
This initial condition is a placeholder. You will need to
establish the condition to be evaluated.
JF 2-8
IF and WHILE Control Structures
11
JF 2-8
IF and WHILE Control Structures
12
JF 2-8
IF and WHILE Control Structures
13
JF 2-8
IF and WHILE Control Structures
14
JF 2-8
IF and WHILE Control Structures
15
If it rains
today,
then
False
Do this: Wear
sweater
Do this: Wear
raincoat
End
JF 2-8
IF and WHILE Control Structures
16
If cat
collides
with dog
Do this: Cat
says, "Excuse
me!"
False
Do this: Cat
continues to
walk
End
JF 2-8
IF and WHILE Control Structures
17
JF 2-8
IF and WHILE Control Structures
18
JF 2-8
IF and WHILE Control Structures
19
JF 2-8
IF and WHILE Control Structures
20
Conditional Execution
The use of conditional control structures allows two types of
loops:
Conditional loop: Stops when a condition is true.
Example: The propeller of a helicopter turns while the helicopter is moving
or flying. If the helicopter stops, then the propeller stops turning.
JF 2-8
IF and WHILE Control Structures
21
JF 2-8
IF and WHILE Control Structures
22
Queen moves
forward
While the
Queen is
collisionfree
False
Queen stops
and turns
around
End
JF 2-8
IF and WHILE Control Structures
23
JF 2-8
IF and WHILE Control Structures
24
JF 2-8
IF and WHILE Control Structures
25
JF 2-8
IF and WHILE Control Structures
26
Terminology
Key terms used in this lesson included:
IF control structure
Process flow
WHILE control structure
JF 2-8
IF and WHILE Control Structures
27
Summary
In this lesson, you should have learned how to:
Use the IF control structure to effect execution of instructions
Use the WHILE control structure to create a conditional loop
for repetitive behavior
JF 2-8
IF and WHILE Control Structures
28
Java Fundamentals
2-9
Expressions
Objectives
This lesson covers the following objectives:
Create an expression to perform a math operation
Interpret a math expression
JF 2-9
Expressions
Using Expressions
Expressions are a combination of values that, when arranged
correctly, result in a final value.
Expressions are typically used in Alice 3 to solve timing and
distance problems in your programs.
Example: 2 + 2 = 4
Two values (2, 2) and the operator (+) result in the final value (4).
JF 2-9
Expressions
Expressions in Alice 3
Expressions are created in Alice 3 using the following built-in
math operators:
Add (+)
Subtract (-)
Multiply (*)
Divide (/)
JF 2-9
Expressions
JF 2-9
Expressions
JF 2-9
Expressions
JF 2-9
Expressions
Distance Problem
The problem: A PlayingCard object moves to the center of the
bookcase, rather than near it.
This is because the getDistanceTo function calculates the
distance from the center of the person object to the center of
the target object (bookcase).
We need to reduce the distance the PlayingCard object
moves so it does not collide with the bookcase.
A math calculation is used to reduce the distance the
PlayingCard object moves.
JF 2-9
Expressions
JF 2-9
Expressions
10
JF 2-9
Expressions
11
JF 2-9
Expressions
12
JF 2-9
Expressions
13
JF 2-9
Expressions
14
Expression Example
This expression reduces the distance that the Playing Card
travels so that it does not collide with the bookcase.
This was tested and debugged several times until the correct
expression was achieved.
With a value of 0.25 the Playing card was still too close.
With a value of 1.0 the distance is correct.
JF 2-9
Expressions
15
JF 2-9
Expressions
16
JF 2-9
Expressions
17
Interpret an Expression
To understand a programming statement that includes an
expression, you often need to interpret the expression.
To interpret an expression you can:
Read it from left to right.
Recognize the instances specified in the expression and
describe what each one does.
JF 2-9
Expressions
18
JF 2-9
Expressions
19
JF 2-9
Expressions
20
Expression Example
Examine the visual associated with this expression.
The hares are moving towards the teacup.
Do you think they will go inside?
JF 2-9
Expressions
21
Interpretation of an Expression
This expression tells us the following:
The marchHare moves forward towards the teacup.
The distance between the marchHare and the teacup is determined by
the getDistanceTo function.
The distance traveled is reduced by half the width of the cave.
The width of the teacup is determined by the getWidth function.
JF 2-9
Expressions
22
Z = Distance moved
X = Distance from marchHare to teacup
a = Teacup width
b=2
JF 2-9
Expressions
23
JF 2-9
Expressions
24
Terminology
Key terms used in this lesson included:
Expression
Math operator
JF 2-9
Expressions
25
Summary
In this lesson, you should have learned how to:
Create an expression to perform a math operation
Interpret a math expression
JF 2-9
Expressions
26
Java Fundamentals
2-10
Variables
White color
1.0 opacity
Objectives
This lesson covers the following objectives:
Understand variables
Understand how variables are used in programming
Viewing Alice code as Java Code on the side
JF 2-10
Variables
Variables
At times, programmers need to store information, and then
use that information in animations or in games.
For example:
The number of times a procedure should be executed.
An object's properties, such as size and color.
A variable is a place in memory where data of a specific type can be
stored for later retrieval and use by your program. Each variable is
given a unique name to make it easy to find and reference. Once a
variable is declared it can be used to store and retrieve data.
JF 2-10
Variables
Variables Example
Below are the variables and their values for a Dalmatian
instance.
1.0 opacity
White color
JF 2-10
Variables
TextString
("Hello World!")
List of objects
JF 2-10
Variables
Object Properties
Object properties are variables that store information about
the object, such as color, width, height, and depth.
Width Variable
Width
JF 2-10
Variables
Description
Perform arithmetic and set the value of a procedure's arguments.
Examples: 0.1, 2.25, 98.6.
Perform arithmetic and set the value of a procedure's arguments.
Examples: 1, 459, 30.
One of two values: true or false.
Usually is the result of tests that compare one thing to another.
The classes of objects that are available in your animation.
Examples: Biped, Scene, Quadruped.
TextString
Other
JF 2-10
Variables
Declaring Variables
To declare (or "create") a variable is to give a variable a name
and to define the type of data the variable will contain.
Variables are declared in the Code editor.
They are useful because they allow you to:
Assign the same value to multiple procedures, such as a distance to
move.
Simultaneously update the value of all arguments in a program that
reference the variable.
Pass information from one procedure to another.
Simplify programming statements using many functions and math
expressions.
JF 2-10
Variables
Initializing Variables
To initialize a variable is to assign it a value. Variables are
initialized in the Code editor at the same time that they are
declared; this is its initial (first assigned) value.
Variable values can be changed as often as you like.
The word "initialize" means "assign a value to".
JF 2-10
Variables
10
JF 2-10
Variables
11
JF 2-10
Variables
12
JF 2-10
Variables
13
Variable Example
The "superSpins" variable is declared and initialized to a
whole number with an initial value of 3.
Use a turn procedure to spin the character
JF 2-10
Variables
14
Variable Example
Each character spins three times.
JF 2-10
Variables
15
JF 2-10
Variables
16
JF 2-10
Variables
17
JF 2-10
Variables
18
JF 2-10
Variables
19
JF 2-10
Variables
20
JF 2-10
Variables
21
JF 2-10
Variables
22
JF 2-10
Variables
23
JF 2-10
Variables
24
25
JF 2-10
Variables
26
Terminology
Key terms used in this lesson included:
Variable
Object properties
Declaring variables
Initializing variables
Java Code on the side
JF 2-10
Variables
27
Summary
In this lesson, you should have learned how to:
Understand variables
Understand how variables are used in programming
Viewing Alice code as Java Code on the side
JF 2-10
Variables
28
Java Fundamentals
2-11
Keyboard Controls
Objectives
This lesson covers the following objectives:
Create an opening sequence
Use keyboard controls to manipulate an animation
Save your Class file
Using the starter tab
Add an existing class file to an animation
JF 2-11
Keyboard Controls
Event Handling
When an animation is playing, a computer program is
running. Many computer programs request user interaction.
These interactive programs allow a user to influence the
order of actions that occur in the program.
To program this type of interactivity into an animation, you
create event listeners that look for and respond to the
interactivity (the user input events) of the user.
This is often referred to as event handling.
JF 2-11
Keyboard Controls
What Is an Event?
An event is any action initiated by the user that is designed to
influence the program's execution during play.
Events may include:
JF 2-11
Keyboard Controls
JF 2-11
Keyboard Controls
Keyboard Controls
Inserting keyboard controls into a program allows the user to
control one or more objects while the animation is running.
The user can press a key on the keyboard, or click the mouse,
to control the next programming action.
JF 2-11
Keyboard Controls
Keyboard Controls
With keyboard controls, you can:
Create scenes where the user controls an object that interacts with
other objects.
Create animations that execute conditionally, based on a key press or
mouse click.
Create games where the user is required to control an object to win the
game.
JF 2-11
Keyboard Controls
JF 2-11
Keyboard Controls
Event Listeners
Event listeners are procedures in the Scene class that listen
for keyboard input while the animation is running.
Keyboard keys can be programmed to:
Move an object up or down when certain keys are pressed.
Move an object forward, backward, left, and right using the arrow keys.
Make an object perform an action, such as speak or disappear.
JF 2-11
Keyboard Controls
10
Scene Activation/Time
Keyboard
Mouse
Position/Orientation
JF 2-11
Keyboard Controls
11
JF 2-11
Keyboard Controls
12
13
JF 2-11
Keyboard Controls
14
15
Keyboard Listeners
Keyboard listeners:
Are found in the Add Event Listener drop-down menu.
Listen for, and react to, a keyboard keystroke that you specify.
JF 2-11
Keyboard Controls
16
Description
addKeyPressListener()
addArrowKeyPressListener()
addNumberKeyPressListener()
addObjectMoverFor(???)
JF 2-11
Keyboard Controls
17
JF 2-11
Keyboard Controls
18
JF 2-11
Keyboard Controls
19
JF 2-11
Keyboard Controls
20
JF 2-11
Keyboard Controls
21
JF 2-11
Keyboard Controls
22
JF 2-11
Keyboard Controls
23
JF 2-11
Keyboard Controls
24
JF 2-11
Keyboard Controls
25
JF 2-11
Keyboard Controls
26
JF 2-11
Keyboard Controls
27
28
JF 2-11
Keyboard Controls
29
Save the file in the MyClasses folder for easy access when
adding it to other animations and name the class with an
appropriate name.
JF 2-11
Keyboard Controls
30
JF 2-11
Keyboard Controls
31
JF 2-11
Keyboard Controls
32
JF 2-11
Keyboard Controls
33
Clicking finish will add the Alice object into your new
animation.
JF 2-11
Keyboard Controls
34
JF 2-11
Keyboard Controls
35
Terminology
Key terms used in this lesson included:
Event
Event handling
Event listeners
Keyboard controls
Keyboard listeners
Class file
JF 2-11
Keyboard Controls
36
Summary
In this lesson, you should have learned how to:
Create an opening Sequence
Use keyboard controls to manipulate an animation
Save your Class file
Using the starter tab
Add an existing class file to an animation
JF 2-11
Keyboard Controls
37
Java Fundamentals
2-12
Develop a Complete Animation
Objectives
This lesson covers the following objectives:
Use functional decomposition to write a scenario and
storyboard
Complete an animation
Test an animation
Reposition objects at run-time
Upload your animation
Plan the presentation of a completed animation project
JF 2-12
Develop a Complete Animation
Animations
An animation is a sequence of actions that simulate
movement.
Use Alice 3 to construct the scene and write the sequence of
actions for your animation, and Alice 3 will render the
animation for you.
Rendering is a process where the software program converts your
code into the animation that you see. Alice 3 renders the animation
based on the instructions provided by the programmer.
JF 2-12
Develop a Complete Animation
JF 2-12
Develop a Complete Animation
JF 2-12
Develop a Complete Animation
Step 2:
Develop a
Solution
Step 3:
Implement the
Solution
Step 4:
Test and Revise
the Solution
Step 2:
Design a
Storyboard
JF 2-12
Develop a Complete Animation
Step 3:
Program the
Animation
Step 4:
Run the
Animation
JF 2-12
Develop a Complete Animation
Scenario
Animation
A firefighter climbs up
the tree to save the cat.
Teach a concept.
Memorizing chemistry
symbols is difficult.
Simulate or demonstrate
a process.
A demonstration shows
how to change a tire on
a virtual car.
Play a game.
An interactive game
maneuvers an airplane
around objects in the
sky.
JF 2-12
Develop a Complete Animation
JF 2-12
Develop a Complete Animation
10
Storyboard Formats
Develop your visual and textual storyboards using a variety of
formats.
Examples:
Draw them on paper with a pencil.
Create them using digital tools such as a word processor, drawing
software, or presentation program.
Write a textual storyboard within Alice 3 in the Code editor using
comments to organize the steps in your program.
JF 2-12
Develop a Complete Animation
11
Visual Storyboards
The visual storyboard helps a reader understand:
JF 2-12
Develop a Complete Animation
12
JF 2-12
Develop a Complete Animation
13
Textual Storyboards
A textual storyboard helps the reader understand the actions
that will take place during the animation.
The moving and non-moving objects can be easily identified
within the action statements, but a more detailed description
may be necessary if multiple programmers are involved in
implementing any scene.
In computing, a textual storyboard is called an algorithm: a list of
actions to perform a task or solve a problem.
JF 2-12
Develop a Complete Animation
14
JF 2-12
Develop a Complete Animation
15
JF 2-12
Develop a Complete Animation
16
Storyboard Components
Textual storyboards should contain the components listed
in the table below
Component
Definition
Examples
Scene
Objects
Actions
User
Interactions
Keyboard commands or
mouse clicks to make
objects move
Design
Specifications
JF 2-12
Develop a Complete Animation
17
Boy
leaves
phone
on bench
False
End
JF 2-12
Develop a Complete Animation
18
JF 2-12
Develop a Complete Animation
19
JF 2-12
Develop a Complete Animation
20
Animation Checklist
During the animation development process, use this checklist
to ensure that your animation meets all animation principles.
JF 2-12
Develop a Complete Animation
21
Declared procedures
Functions
Movement procedures
Random numbers
Math expressions
Variables
Keyboard controls
JF 2-12
Develop a Complete Animation
22
JF 2-12
Develop a Complete Animation
23
Debugging Tasks
Test and debug the animation frequently as it is being
developed.
Use some of the following debugging techniques:
Adjust the direction, distance, and duration that objects move.
Adjust math calculations that help refine the distance or duration that
objects move.
Refine instructions in the code that do not work as intended.
Resolve errors created by the programmer.
JF 2-12
Develop a Complete Animation
24
JF 2-12
Develop a Complete Animation
25
JF 2-12
Develop a Complete Animation
26
JF 2-12
Develop a Complete Animation
27
JF 2-12
Develop a Complete Animation
28
JF 2-12
Develop a Complete Animation
29
JF 2-12
Develop a Complete Animation
30
31
JF 2-12
Develop a Complete Animation
32
JF 2-12
Develop a Complete Animation
33
JF 2-12
Develop a Complete Animation
34
JF 2-12
Develop a Complete Animation
35
JF 2-12
Develop a Complete Animation
36
JF 2-12
Develop a Complete Animation
37
JF 2-12
Develop a Complete Animation
38
JF 2-12
Develop a Complete Animation
39
Group Presentations
If you will be making your presentation with a group, here are
some steps your group can follow to make sure all group
members have a part in preparing and delivering the
presentation.
Include all group members in all steps of the presentation
planning.
Divide presentation tasks equally among group members.
Practice the presentation as a group, and give one another
constructive feedback immediately following.
JF 2-12
Develop a Complete Animation
40
Terminology
Key terms used in this lesson included:
Algorithm
Animation checklist
Debugging
Comments
Functional decomposition
Rendering
Scenario
Textual storyboard
Visual storyboard
JF 2-12
Develop a Complete Animation
41
Summary
In this lesson, you should have learned how to:
Use functional decomposition to write a scenario and
storyboard
Complete an animation
Test an animation
Reposition objects at run-time
Upload your animation
Plan the presentation of a completed animation project
JF 2-12
Develop a Complete Animation
42
Java Fundamentals
2-13
Java Variables and Data Types
Objectives
This lesson covers the following objectives:
Describe variables
Describe Java simple types
Define arithmetic operators
Describe relational and logical operators
Describe assignment operators
JF 2-13
Java Variables and Data Types
Java
JF 2-13
Java Variables and Data Types
Variables in Alice 3
Variables are declared (created) in your code.
A typical application uses various values which continuously
change while the program is running.
For example, in Alice 3, a car is programmed to roll over a
certain number of times.
The value entered by one user may be different from the
value entered by another user.
JF 2-13
Java Variables and Data Types
JF 2-13
Java Variables and Data Types
Object Properties
Object properties are variables that store information about
the object, such as its color, height, and depth.
JF 2-13
Java Variables and Data Types
JF 2-13
Java Variables and Data Types
here.
while(i<=7){
for(j=1; j<=i; j++)
System.out.println("*");
i=i+2;
System.out.println();
}
}
}
JF 2-13
Java Variables and Data Types
JF 2-13
Java Variables and Data Types
10
Description
Perform arithmetic and set the value of a procedure's arguments.
Examples: 0.1, 2.25, 98.6.
Perform arithmetic and set the value of a procedure's arguments.
Examples: 1, 459, 30.
One of two values: true or false.
Usually is the result of tests that compare one thing to another.
Any object in Alice 3 like a cat, dog, person, etc.
The classes of objects in your animation.
Examples: Biped, Scene, Quadruped.
TextString
Other
JF 2-13
Java Variables and Data Types
11
JF 2-13
Java Variables and Data Types
12
boolean
1 bit
True, false
byte
1 byte (8 bits)
12, 128
char
2 bytes
2 bytes
6, -14, 2345
JF 2-13
Java Variables and Data Types
-32,768 to 32,767
13
int
6, -14, 2345
4 bytes
long
float
double
8 bytes
4 bytes
8 bytes
3459111, 2
-9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
3.145, .077
.0000456, 3.7
JF 2-13
Java Variables and Data Types
14
JF 2-13
Java Variables and Data Types
15
JF 2-13
Java Variables and Data Types
16
17
Relational Operators
Relational operators include:
=
>
<
JF 2-13
Java Variables and Data Types
18
JF 2-13
Java Variables and Data Types
19
Operator Name
Example
==
Equal To
(A == B) is false
!=
Not Equal To
(A != B) is true
>
Greater Than
(A > B) is false
>=
(A >= B) is false
<
Less Than
(A < B) is true
<=
(A <= B) is true
JF 2-13
Java Variables and Data Types
20
== b = " + (a == b) );
!= b = " + (a != b) );
> b = " + (a > b) );
< b = " + (a < b) );
>= a = " + (b >= a) );
<= a = " + (b <= a) );
JF 2-13
Java Variables and Data Types
21
JF 2-13
Java Variables and Data Types
22
JF 2-13
Java Variables and Data Types
23
Operator Name
&&
||
NOT
JF 2-13
Java Variables and Data Types
24
JF 2-13
Java Variables and Data Types
25
JF 2-13
Java Variables and Data Types
26
JF 2-13
Java Variables and Data Types
27
28
JF 2-13
Java Variables and Data Types
29
Example
Equivalent To
+=
x += y
x = x + y;
-=
x -= y
x = x - y;
*=
x *= y
x = x * y;
/=
x /= y
x = x / y;
JF 2-13
Java Variables and Data Types
30
31
Terminology
Key terms used in this lesson included:
Arithmetic operators
Assignment operators
Data type
Logical operators
Relational operators
Variable
JF 2-13
Java Variables and Data Types
32
Summary
In this lesson, you should have learned how to:
Describe variables
Describe Java simple types
Define arithmetic operators
Describe relational and logical operators
Describe assignment operators
JF 2-13
Java Variables and Data Types
33
Java Fundamentals
2-14
Java Methods and Classes
Objectives
This lesson covers the following objectives:
Describe a method, class, and instance
Describe a scenario where an IF control structure would be
used
Describe a scenario where a WHILE control structure would
be used
Recognize the syntax for a method, class, function, and
procedure
Describe input and output
JF 2-14
Java Methods and Classes
Java
JF 2-14
Java Methods and Classes
Procedures in Alice 3
In Alice 3, a procedure is a piece of code that sends a
message to an object asking it to perform an action.
A procedure does not return a value.
A set of procedures are available for each class.
JF 2-14
Java Methods and Classes
JF 2-14
Java Methods and Classes
JF 2-14
Java Methods and Classes
Methods in Java
Methods in Java are the same as procedures in Alice 3.
A method is a piece of code that sends a message to an
object asking it to perform an action. Methods:
Belong to a class.
Are referred to by name.
Can be called at any point in a program using the method's name.
JF 2-14
Java Methods and Classes
statement;
JF 2-14
Java Methods and Classes
Method 1
JF 2-14
Java Methods and Classes
10
Method Properties
Method Property
Description
modifiers
dataType
methodName
parameterList
methodBody
return
Keyword that sends the result value back to the code that
called the method.
JF 2-14
Java Methods and Classes
11
findMax() Method
public class TestFindMax {
/** Main method */
public static void main(String[] args) {
int i = 5;
int j = 2;
int k = findMax(i, j);
System.out.println("The maximum between " + i + " and " + j +
" is " + k);
}//end method main
/** Return the max between two numbers */
public static int findMax(int num1, int num2) {
int result;
if (num1 > num2)
result = num1;
else
findMax Method
result = num2;
//endif
return result;
}//end method findMax
JF 2-14
Java Methods and Classes
12
Classes in Alice 3
A Dalmatian is a dog. When a Dalmatian object is added to a
scene, it has the properties of the Dalmatian class: four legs,
two ears, a white and black spotted coat, and the ability to
walk.
A class is a specification, such as a blueprint or pattern, of how to
construct an object.
JF 2-14
Java Methods and Classes
13
Classes in Java
The first group:
Optional; refers to the visibility from other objects.
public means visible everywhere.
The default is package or visible within the current package only.
["public"] ["abstract"|"final"]"class" Class_name
["extends" object_name] ["implements" interface_name]
"{"
// properties declarations
// behavior declarations
"}"
JF 2-14
Java Methods and Classes
14
Classes in Java
The second group:
Optional; defines whether the class can be inherited or extended by
other classes.
Abstract classes must be extended and final classes can never be
extended by inheritance.
The default indicates that the class may or may not be extended at the
programmers discretion.
["public"] ["abstract"|"final"]"class" Class_name
["extends" object_name] ["implements" interface_name]
"{"
// properties declarations
// behavior declarations
"}"
JF 2-14
Java Methods and Classes
15
Classes in Java
Class_name is the name of the class.
The third option of extends is related to inheritance.
The fourth option of implements is related to interfaces.
["public"] ["abstract"|"final"]"class" Class_name
["extends" object_name] ["implements" interface_name]
"{"
// properties declarations
// behavior declarations
"}"
JF 2-14
Java Methods and Classes
16
17
Instances in Alice 3
When you add an object to a scene, this creates an instance
of the class.
An object is an instance of a class.
JF 2-14
Java Methods and Classes
18
Instances in Java
In the main method, the myCat instance of the cat class is
created.
class Cat{
int catAge;
String catName;
JF 2-14
Java Methods and Classes
19
JF 2-14
Java Methods and Classes
20
Control Structures
Control structures allow you to change the order of how the
statements in your programs are executed.
Both Alice and Java allow for these types of control
structures.
Type
Description
Example
Decision
Control
Structures
if then else
Repetition
Control
Structures
while loop
JF 2-14
Java Methods and Classes
21
if Control Structure
if control structures are statements that allow you to select
and execute specific blocks of code while skipping other
sections.
These structures have the following form.
if (boolean_expression) {
doSomething();
}
else {
doSomethingElse();
}//endif
JF 2-14
Java Methods and Classes
22
JF 2-14
Java Methods and Classes
23
24
JF 2-14
Java Methods and Classes
25
JF 2-14
Java Methods and Classes
26
JF 2-14
Java Methods and Classes
27
JF 2-14
Java Methods and Classes
28
JF 2-14
Java Methods and Classes
29
Terminology
Key terms used in this lesson included:
Class
Control structure
IF control structure
Instance
Method
WHILE control structure
JF 2-14
Java Methods and Classes
30
Summary
In this lesson, you should have learned how to:
Describe a method, class, and instance
Describe a scenario where an IF control structure would be
used
Describe a scenario where a WHILE control structure would
be used
Recognize the syntax for a method, class, function, and
procedure
Describe input and output
JF 2-14
Java Methods and Classes
31
Java Fundamentals
3-1
Getting Started with Greenfoot
Objectives
This lesson covers the following objectives:
Download and install Greenfoot
Describe the components of the Greenfoot interactive
development environment
Create an instance of a class
Describe classes and subclasses
Recognize Java syntax used to correctly create a subclass
JF 3-1
Getting Started with Greenfoot
Launch Greenfoot
To launch Greenfoot:
Double-click the Greenfoot icon on your desktop.
Select the Greenfoot program from your list of computer programs.
JF 3-1
Getting Started with Greenfoot
JF 3-1
Getting Started with Greenfoot
JF 3-1
Getting Started with Greenfoot
JF 3-1
Getting Started with Greenfoot
Execution Controls
Execution controls to run a scenario include:
Act: Runs all actions in the scenario once.
Run/pause: Runs all actions in the scenario repeatedly until Pause is
clicked.
Reset: Pauses the scenario or resets the scenario back to its starting
position.
Speed: Runs actions faster or slower.
JF 3-1
Getting Started with Greenfoot
Inherited Characteristics
In nature, a bee inherits some characteristics that are
common to all bees: six legs and two wings.
The bee may also inherit the characteristics of its breed that
gives it a specific color, shape and size.
In Greenfoot, a class, such as the Bee class, defines the
characteristics of all bee objects that act in the scenario, such
as how they look and ways they can act.
A class contains the specifications that define the appearance and
movement of an object. The class provides instructions to Greenfoot
for how to create and display instances when they are added to your
scenario.
JF 3-1
Getting Started with Greenfoot
Classes in Greenfoot
The class tells your scenario how its objects should look and
act when the scenario is run.
When you add a class to your scenario, it appears in the class
hierarchy (to the right of the world).
You can add as many instances of the class as you wish to the
scenario.
JF 3-1
Getting Started with Greenfoot
10
Superclass Types
Two types of superclasses appear in the Greenfoot class
hierarchy:
World:
Holds the subclasses that provide the background image for the scenario's
world.
Defines the size and resolution of the world.
Actor:
Holds the subclasses that produce the
instances that act in the scenario.
JF 3-1
Getting Started with Greenfoot
11
Subclasses
Subclasses are a specialization of a class.
For example, the Bee class is a subclass of the Actor
superclass. This subclass:
Inherits all of the properties of the Actor superclass, such as a predefined set of actions that Actor subclasses can perform.
Has properties specific to its subclass, such as the image that gives bee
objects their appearance.
Can receive new properties that the programmer creates specifically
for the subclass, such as images or actions.
JF 3-1
Getting Started with Greenfoot
12
Subclass Properties
A subclass has an "is-a" relationship to a superclass (Bee is a
subclass of the Actor superclass).
Properties can be modified (such as the class's name, image
to display, or actions to perform).
An arrow in the class hierarchy shows the subclass's
relationship to the superclass.
JF 3-1
Getting Started with Greenfoot
13
JF 3-1
Getting Started with Greenfoot
14
JF 3-1
Getting Started with Greenfoot
15
16
Compilation
Once a new subclass is created and displayed in the class
hierarchy, it has stripes across it.
Stripes indicate that compilation is required.
Compilation is required:
When the class's source code has been modified.
When a subclass or superclass is created or modified.
Compilation translates the source code into machine code that the
computer can understand. The striped appearance ensures that you
added the source code or class correctly before you proceed.
JF 3-1
Getting Started with Greenfoot
17
JF 3-1
Getting Started with Greenfoot
18
JF 3-1
Getting Started with Greenfoot
19
JF 3-1
Getting Started with Greenfoot
20
Instances of a Class
The Bee class has characteristics such as movement, color,
and size.
A Bee that flies in a field, or rests in a flower, is a physical
object that is a unique instance of the Bee class.
An instance holds the characteristics of the class, but can be
manipulated and changed.
JF 3-1
Getting Started with Greenfoot
21
Greenfoot Instances
One or many instances of a class can be added to the
scenario.
Actor instances move and act in your scenario.
World instances provide the background for your scenario.
JF 3-1
Getting Started with Greenfoot
22
JF 3-1
Getting Started with Greenfoot
23
Source Code
DNA gives humans certain characteristics, such as
appearance, mobility, and communication.
Like DNA, source code is written to tell the class how its
instances could act in the scenario.
Source code defines what all instances of each class are capable of
doing. The behavior of each instance is determined by the source
code of its class.
JF 3-1
Getting Started with Greenfoot
24
JF 3-1
Getting Started with Greenfoot
25
Code Editor
The Code editor displays the class's source code.
This is where instructions are programmed for how instances
of the class can act in the scenario.
JF 3-1
Getting Started with Greenfoot
26
Terminology
Key terms used in this lesson included:
Class
Compilation
Instance
Source code
Subclass
Superclass
JF 3-1
Getting Started with Greenfoot
27
Summary
In this lesson, you should have learned how to:
Download and install Greenfoot
Describe the components of the Greenfoot interactive
development environment
Create an instance of a class
Describe classes and subclasses
Recognize Java syntax used to correctly create a subclass
JF 3-1
Getting Started with Greenfoot
28
Java Fundamentals
3-2
Methods, Variables, and Parameters
Objectives
This lesson covers the following objectives:
Define parameters and how they are used in methods
Understand inheritance
Describe properties of an object
Examine the purpose of a variable
Discuss programming concepts and define terminology
JF 3-2
Methods, Variables, and Parameters
Methods Example
In order to complete a task, such as math homework, there
are several subtasks:
Student completes the math homework.
Student goes to school.
Student submits the homework to their teacher.
Because of learned experiences in school, combined with preprogrammed abilities (such as thinking), the student is
capable of completing this task.
JF 3-2
Methods, Variables, and Parameters
Methods
In programming, each object has a set of operations (or tasks)
it can perform.
Programmers write a program to tell an object how and when
to perform tasks, such as:
Command an object to perform an action.
Ask an object a question to learn more about what it does.
Methods are a set of operations or tasks that instances of a class can
perform. When a method is invoked, it will perform the operation or
task specified in the source code.
JF 3-2
Methods, Variables, and Parameters
Inheritance
Greenfoot objects inherit the methods and properties of their
class and superclass.
For example, an Alligator instance would inherit the methods
of the Actor superclass and Alligator class.
Inheritance means that each subclass inherits its methods from its
superclass.
JF 3-2
Methods, Variables, and Parameters
JF 3-2
Methods, Variables, and Parameters
JF 3-2
Methods, Variables, and Parameters
Method Summary
The method summary displays the class's inherited methods.
JF 3-2
Methods, Variables, and Parameters
Method Components
A method has several components that describe the
operations or tasks it performs.
Return type: Specifies the type of data that the method returns.
Method name: Describes what the method does.
Parameter list: Information that goes into the method call.
Examples of methods:
void move(3)
int getX()
10
Method Signature
The method signature describes the intentions of the
method.
It includes the following components:
Method name
Parameter list
void move(int)
Method
name
Parameter List
()
JF 3-2
Methods, Variables, and Parameters
11
Return Types
The return type is the word at the beginning of the method
that indicates what type of information a method call will
return.
There are two types of return types:
Void: No data return - Issues a command to the object.
Non-void: Returns Data - Asks the object a question.
void move(int)
Return
type
JF 3-2
Methods, Variables, and Parameters
12
JF 3-2
Methods, Variables, and Parameters
13
JF 3-2
Methods, Variables, and Parameters
14
JF 3-2
Methods, Variables, and Parameters
15
JF 3-2
Methods, Variables, and Parameters
16
Boolean
Returns a true or false value.
Types of questions it may ask an object:
Are you touching another object?
Are you at the edge of the world?
JF 3-2
Methods, Variables, and Parameters
17
Method Parameters
Parameters provide methods with additional data to make an
object perform a task, when information is required to invoke
the method.
Parameters are defined by two components:
Parameter type
Parameter name
Parameters are used to command objects to move, or to tell objects
what type of response is expected when we ask an object a question.
JF 3-2
Methods, Variables, and Parameters
18
JF 3-2
Methods, Variables, and Parameters
19
JF 3-2
Methods, Variables, and Parameters
20
Object Properties
Object properties describe the instance's appearance and
abilities, such as:
Size
Color
Range of movements
JF 3-2
Methods, Variables, and Parameters
21
Variables
A variable, or field, allows the instance to store information to
use immediately or later.
For example, object properties are variables that store
information about the instance, such as its position in the
world.
Instance variables are the memory that belong to the instance of the
class. That memory can be saved and accessed later as long as the
instance exists.
JF 3-2
Methods, Variables, and Parameters
22
JF 3-2
Methods, Variables, and Parameters
23
Programming Syntax
The source code specifies all of the properties and
characteristics of a class and its objects.
Write source code (also known as syntax) in the class's Code
editor to command objects in your scenario to act.
JF 3-2
Methods, Variables, and Parameters
24
JF 3-2
Methods, Variables, and Parameters
25
Act Method
Whenever the Act or Run execution controls are clicked in the
environment, the object will repeatedly do what is
programmed in the act method.
JF 3-2
Methods, Variables, and Parameters
26
JF 3-2
Methods, Variables, and Parameters
27
JF 3-2
Methods, Variables, and Parameters
28
JF 3-2
Methods, Variables, and Parameters
29
30
JF 3-2
Methods, Variables, and Parameters
31
JF 3-2
Methods, Variables, and Parameters
32
Error Explanations
Click the question mark (?) to display a more detailed error
message that attempts to explain the error.
Not all error messages will be easy to understand.
JF 3-2
Methods, Variables, and Parameters
33
Terminology
Key terms used in this lesson included:
Debug
Inheritance
Instance variable
Method
Method call
Parameter
Return type
Method signature
Variable
JF 3-2
Methods, Variables, and Parameters
34
Summary
In this lesson, you should have learned how to:
Define parameters and how they are used in methods
Understand inheritance
Describe properties of an object
Examine the purpose of a variable
Discuss programming concepts and define terminology
JF 3-2
Methods, Variables, and Parameters
35
Java Fundamentals
3-3
Source Code and Documentation
Objectives
This lesson covers the following objectives:
Demonstrate source code changes to invoke methods
programmatically
Demonstrate source code changes to write an if decision
statement
Describe a method to display object orientation
JF 3-3
Source Code and Documentation
Source Code
Source code is the blueprint or map that defines how your
objects and program function.
It commands the objects in your scenario to move and
interact.
JF 3-3
Source Code and Documentation
Code Editor
Source code is managed in the Code editor.
To view the Code editor, right click on any class in the
environment, then select Open editor from the menu.
JF 3-3
Source Code and Documentation
JF 3-3
Source Code and Documentation
Class Description
act() Method
Method Signature
Method Body
Comments
Documentation
Class Definition
JF 3-3
Source Code and Documentation
Class Description
The class description is a
set of comments that can
be modified to describe
the class.
This includes:
A description of what the
class does.
The name of the person who
authored the code.
The date the source code
was last modified.
JF 3-3
Source Code and Documentation
Java keywords or
reserved words
(public, class)
Java keywords or
reserved words
(extends)
JF 3-3
Source Code and Documentation
Superclass
JF 3-3
Source Code and Documentation
10
act() Method
The act() method is the part of the class definition that tells
objects which methods to perform when the Act or Run
execution controls are clicked in the environment.
JF 3-3
Source Code and Documentation
11
Defining Classes
The class definition defines:
Variables (or fields) that store data persistently within an instance.
Constructors that initially set up an instance.
Methods that provide the behaviors for an instance.
JF 3-3
Source Code and Documentation
12
Method Signature
The method signature describes what the method does.
The signature contains a method name and parameter list.
Method name
Parameter list ()
JF 3-3
Source Code and Documentation
13
Comments
Comments describe what the source code does.
Do not impact the functionality of the program.
Start with a forward slash and two asterisks /** or simply a double
forward slash.
End /** comments with */
Written in blue font (in Greenfoot).
JF 3-3
Source Code and Documentation
14
Documentation
Documentation describes the properties of the class.
To view, select Documentation from the drop-down menu at
the top right of the Code editor.
JF 3-3
Source Code and Documentation
15
JF 3-3
Source Code and Documentation
16
Method name
Parameter list to indicate the type of arguments to invoke, if required.
Semicolon to mark the end of the method call.
JF 3-3
Source Code and Documentation
17
Parameters
Semicolon
JF 3-3
Source Code and Documentation
18
JF 3-3
Source Code and Documentation
19
Description
void act()
JF 3-3
Source Code and Documentation
20
JF 3-3
Source Code and Documentation
21
Sequential Tasks
A single task, such as going to school, requires multiple subtasks:
Wake up
Take a shower
Brush your teeth
Get dressed
JF 3-3
Source Code and Documentation
22
Sequential Methods
Sequential methods are multiple methods executed by
Greenfoot in the order in which they are written in the
program.
These methods make it possible for an object to perform
sequential tasks, such as run and then jump, or play a sound
after something explodes.
Objects can be programmed to perform sequential methods
whenever the Act button is clicked.
JF 3-3
Source Code and Documentation
23
if-then Relationships
Many things around us have a cause and effect relationship,
or "if-then" relationship.
If your cell phone rings, then you answer it. If it doesn't ring, then you
do not answer it.
If a flower starts to wilt, then you give it water. If the flower looks
healthy, then you do not give it water.
JF 3-3
Source Code and Documentation
24
if Decision Statements
An IF statement is written to tell your program to execute a
set of programming statements only if and when a certain
condition is true.
if (condition)
{
instruction;
instruction;
JF 3-3
Source Code and Documentation
25
Condition
Method calls
JF 3-3
Source Code and Documentation
26
JF 3-3
Source Code and Documentation
27
isKeyDown Method
The isKeyDown method is a pre-existing Greenfoot method
that listens to determine if a keyboard key is pressed during
program execution.
This method is called in a class using dot notation.
When a method is not in the class or inherited by the class you are
programming, specify the class or object that has the method before
the method name, then a dot, then the method name. This technique
is called dot notation.
JF 3-3
Source Code and Documentation
28
JF 3-3
Source Code and Documentation
29
JF 3-3
Source Code and Documentation
30
Description
int getRotation()
World getWorld()
int getX()
int getY()
JF 3-3
Source Code and Documentation
31
JF 3-3
Source Code and Documentation
32
Terminology
Key terms used in this lesson included:
Class description
Comments
if decision statements
Invoking a method
Object oriented analysis
Sequential methods
JF 3-3
Source Code and Documentation
33
Summary
In this lesson, you should have learned how to:
Demonstrate source code changes to invoke methods
programmatically
Demonstrate source code changes to write an if decision
statement
Describe a method to display object orientation
JF 3-3
Source Code and Documentation
34
Java Fundamentals
3-4
Developing and Testing an Application
Objectives
This lesson covers the following objectives:
Demonstrate program testing strategies
Recognize phases for developing a software application
JF 3-4
Developing and Testing an Application
JF 3-4
Developing and Testing an Application
JF 3-4
Developing and Testing an Application
JF 3-4
Developing and Testing an Application
Ensure all string quotes are double " not single '.
JF 3-4
Developing and Testing an Application
Auto-Layout
A useful function within the Greenfoot code editor is the
Auto-Layout feature.
You will find this automatically structures your code and is a
great tool to find where your missing brackets are!
JF 3-4
Developing and Testing an Application
JF 3-4
Developing and Testing an Application
Analysis Phase
In the analysis phase, determine what problem the game will
solve, or the task it will perform, using object oriented
analysis.
In object oriented analysis, Java programmers analyze a problem and
then create objects to build a system, or more specifically, to solve the
problem.
JF 3-4
Developing and Testing an Application
10
11
Analysis Example
Analysis Item
Description
Problem domain
Objects
Objects operations
JF 3-4
Developing and Testing an Application
12
Example
Numerical representations
and limitations.
JF 3-4
Developing and Testing an Application
13
Design Phase
The solution you design will be in the form of a Greenfoot
game that your target audience can play.
Design your game in a textual storyboard that plans the
algorithms, or methods, that objects will perform in response
to keyboard commands or mouse clicks.
JF 3-4
Developing and Testing an Application
14
JF 3-4
Developing and Testing an Application
15
16
Development Phase
After you finalize your storyboard, develop your game in
Greenfoot.
Refer to your storyboard to determine the methods you need
to program.
JF 3-4
Developing and Testing an Application
17
Testing Phase
After you write a section of code, compile it, then test it by
clicking the Run button in the environment.
Observe the game then revise the code as necessary.
For quality assurance purposes:
Have other people test your game and give you feedback.
Seek people who fit the target audience for your game.
18
JF 3-4
Developing and Testing an Application
19
JF 3-4
Developing and Testing an Application
20
Terminology
Key terms used in this lesson included:
Bugs
Documentation
JF 3-4
Developing and Testing an Application
21
Summary
In this lesson, you should have learned how to:
Demonstrate program testing strategies
Recognize phases for developing a software application
JF 3-4
Developing and Testing an Application
22
Java Fundamentals
3-5
Randomization and Constructors
Objectives
This lesson covers the following objectives:
Create randomized behaviors
Define comparison operators
Create if-else control statements
Create an instance of a class
Recognize and describe dot notation
JF 3-5
Randomization and Constructors
getRandomNumber Method
The getRandomNumber method is a static method that
returns a random number between zero and a parameter
limit.
This method is used to eliminate predictability in your
program.
Method signature:
public static int getRandomNumber(int limit)
JF 3-5
Randomization and Constructors
Dot Notation
New subclasses that you create do not inherit the
getRandomNumber method.
This method must be called from the Greenfoot class using
dot notation.
Example :
Greenfoot.getRandomNumber(20);
When you want to use a method but it is not inherited by the class
you are programming, specify the class or object that has the method
before the method name, then a dot, then the method name. This
technique is called dot notation.
JF 3-5
Randomization and Constructors
className.methodName (parameters);
objectName.methodName (parameters);
JF 3-5
Randomization and Constructors
JF 3-5
Randomization and Constructors
Greenfoot API
Reference the Greenfoot Application Programmers' Interface
(API) to examine additional methods to call using dot
notation.
The Greenfoot Application Programmers' Interface lists all of the
classes and methods available in Greenfoot.
JF 3-5
Randomization and Constructors
JF 3-5
Randomization and Constructors
JF 3-5
Randomization and Constructors
10
Comparison Operators
Use comparison operators to compare a randomized value to
another value in a control statement.
The example below determines if the random number is less
than 20.
If it is, then the object turns ten degrees.
if (Greenfoot.getRandomNumber(100) < 20)
{
turn(10);
}
JF 3-5
Randomization and Constructors
11
Description
<
Less than
>
Greater than
<=
>=
==
Equal
!=
Not equal
JF 3-5
Randomization and Constructors
12
Solution:
The Fly should turn a small amount as it moves.
To code this solution, turn the Fly a random number of degrees, up to
20 degrees, 10% of the time as it moves.
if (Greenfoot.getRandomNumber(100) < 10)
{
turn(Greenfoot.getRandomNumber(20));
}
JF 3-5
Randomization and Constructors
13
Method body with statement to indicate that the object should turn up
to 20 degrees if the condition is true.
if (Greenfoot.getRandomNumber(100) < 10)
{
turn(Greenfoot.getRandomNumber(20));
}
JF 3-5
Randomization and Constructors
14
JF 3-5
Randomization and Constructors
15
Conditional Behavior
Instances can be programmed to perform specific behaviors if
a condition is not met, using an if-else statement.
For example, if an instance is programmed to turn 6% of the
time, what does it do the other 94% of the time?
An if-else statement executes its first code segment if a condition is
true, and its second code segment if a condition is false, but not both.
JF 3-5
Randomization and Constructors
16
True
Evaluate
the
Condition
False
Execute ELSE
Statement
Execute IF
Statement
JF 3-5
Randomization and Constructors
17
if (condition)
{
statements;
}
else
{
statements;
}
JF 3-5
Randomization and Constructors
18
JF 3-5
Randomization and Constructors
19
JF 3-5
Randomization and Constructors
20
Solution:
Program instances to be automatically added to the world when the
scenario is initialized.
JF 3-5
Randomization and Constructors
21
Comment
Constructor
JF 3-5
Randomization and Constructors
22
Constructors
Constructors:
Define the instance's size and resolution.
Have no return type.
Have the same name as the name of the class. For example, a World
constructor is named World.
A constructor is a special kind of method that is automatically
executed when a new instance of the class is created.
JF 3-5
Randomization and Constructors
23
Size
Resolution
JF 3-5
Randomization and Constructors
24
JF 3-5
Randomization and Constructors
25
addObject Method
The addObject method is a World class method that adds a
new object to the world at specific x and y coordinates.
It includes:
Keyword new to tell Greenfoot to create a new object of a specific
class.
Method parameters:
Named object from Actor class.
Integer value of X coordinate.
Integer value of Y coordinate.
Method definition:
void addObject(Actor object, int x, int y)
JF 3-5
Randomization and Constructors
26
new Keyword
The new keyword creates new instances of existing classes.
It starts with the keyword new, followed by the constructor to
call.
The parameter list passes arguments (values) to the constructor that
are needed to initialize the object's instance variables.
The default constructor has an empty parameter list and sets the
object's instance variables to their default values.
new ConstructorName()
JF 3-5
Randomization and Constructors
27
Y
JF 3-5
Randomization and Constructors
28
JF 3-5
Randomization and Constructors
29
JF 3-5
Randomization and Constructors
30
JF 3-5
Randomization and Constructors
31
Terminology
Key terms used in this lesson included:
Comparison operators
Constructor
Dot notation
new Keyword
JF 3-5
Randomization and Constructors
32
Summary
In this lesson, you should have learned how to:
Create randomized behaviors
Define comparison operators
Create if-else control statements
Create an instance of a class
Recognize and describe dot notation
Save the World feature
JF 3-5
Randomization and Constructors
33
Java Fundamentals
3-6
Defining Methods
Objectives
This lesson covers the following objectives:
Describe effective placement of methods in a super or
subclass
Simplify programming by creating and calling defined
methods
Handling collisions
JF 3-6
Defining Methods
JF 3-6
Defining Methods
Defined Methods
Defined methods are new methods created by the
programmer.
These methods:
Can be executed immediately, or stored and called later.
Do not change the behavior of the class when stored.
Separate code into shorter methods, making it easier to read.
Defined methods create a new method that a class did not already
possess. These methods are written in the class's source code below
the act method.
JF 3-6
Defining Methods
JF 3-6
Defining Methods
JF 3-6
Defining Methods
Solution:
Create a subclass of Actor that defines a method that can detect if the
object is at the edge of the world and to turn appropriately.
Call the new methods in the subclasses that should be able to turn and
move at the edge of the world.
JF 3-6
Defining Methods
JF 3-6
Defining Methods
JF 3-6
Defining Methods
10
Logic Operators
Logic operators can be used to combine multiple boolean expressions
into one boolean expression.
Logic Operator
Means
Definition
NOT
AND
OR
Double ampersand
(&&)
JF 3-6
Defining Methods
11
JF 3-6
Defining Methods
12
JF 3-6
Defining Methods
13
JF 3-6
Defining Methods
14
JF 3-6
Defining Methods
15
JF 3-6
Defining Methods
16
JF 3-6
Defining Methods
17
JF 3-6
Defining Methods
18
JF 3-6
Defining Methods
19
JF 3-6
Defining Methods
20
Class Documentation
The Bug class documentation shows the new method after its
defined.
All subclasses of the Bug superclass inherit this method.
JF 3-6
Defining Methods
21
Collisions
Most game projects will usually have to detect when two
actors touch which is usually called a collision.
In GreenFoot there are multiple ways to detect this.
Some of these are
isTouching()
getOneIntersectingObject(Class)
getOneObjectAtOffset(Class)
getIntersectingObjects(Class)
getNeighbours(distance,diagonal)
getObjectsAtOffset(dx,dy,Class)
JF 3-6
Defining Methods
22
Collisions
Method
When To Use
isTouching
getOneIntersectingObjec
t
getOneObjectAtOffset
JF 3-6
Defining Methods
23
JF 3-6
Defining Methods
24
JF 3-6
Defining Methods
25
JF 3-6
Defining Methods
26
JF 3-6
Defining Methods
27
Terminology
Key terms used in this lesson included:
Defined methods
Collisions
JF 3-6
Defining Methods
28
Summary
In this lesson, you should have learned how to:
Describe effective placement of methods in a super or
subclass
Simplify programming by creating and calling defined
methods
JF 3-6
Defining Methods
29
Java Fundamentals
3-7
Sound and Keyboard Control
Objectives
This lesson covers the following objectives:
Write programming statements to include sound in a program
Write programming statements to include keyboard
movements in a program
Write programming statements to include mouse interaction
in a program
Write programming statements to retrieve information from
the user.
JF 3-7
Sound and Keyboard Control
Keyboard Controls
Games are controlled by a human or computer player using a
remote control or keyboard controls.
To make a scenario behave like a true game, program
statements that include keyboard controls so the player can
control one or more objects in the game.
JF 3-7
Sound and Keyboard Control
Method signature:
public static boolean isKeyDown(String key)
JF 3-7
Sound and Keyboard Control
JF 3-7
Sound and Keyboard Control
JF 3-7
Sound and Keyboard Control
Sound Example
The playSound method is called using dot notation in the
body of the catchFly method.
Whenever the Bee object catches a fly, it makes a sound.
JF 3-7
Sound and Keyboard Control
10
JF 3-7
Sound and Keyboard Control
11
12
JF 3-7
Sound and Keyboard Control
13
JF 3-7
Sound and Keyboard Control
14
JF 3-7
Sound and Keyboard Control
15
Would produce
JF 3-7
Sound and Keyboard Control
16
Terminology
Key terms used in this lesson included:
Keyboard control
Play Sounds
Mouse Interaction
Ask
JF 3-7
Sound and Keyboard Control
17
Summary
In this lesson, you should have learned how to:
Write programming statements to include sound in a program
Write programming statements to include keyboard
movements in a program
Write programming statements to receive the mouse state.
Write programming statements to retrieve a response from
the user.
JF 3-7
Sound and Keyboard Control
18
Java Fundamentals
3-8
World, Animation, and Game End
Objectives
This lesson covers the following objectives:
Construct a world object using a constructor method
Create an object using a constructor
Write programming statements to use the new keyword
Define the purpose and syntax of a variable
Recognize the syntax to define and test variables
Write programming statements to switch between two
images
Write programming statements to end a game
JF 3-8
World, Animation, and Game End
Constructors
When a new World subclass is created and compiled,
Greenfoot executes a constructor that creates an instance of
it to display in the scenario.
Constructors set up the instance and establish an initial state,
such as the size and resolution of the instance.
Constructors have no return type.
Their name, immediately following the word "public," is the same as
the class in which they are defined.
Constructors are special methods that are executed automatically
whenever a new instance of the class is created.
JF 3-8
World, Animation, and Game End
Constructor Parameters
A constructor's parameters allow an instance's initial values
to be passed into the constructor.
These parameters:
Are only available to the instance created by the constructor.
Have a restricted scope limited to when the constructor is declared.
Have a restricted lifetime limited to the single execution of the
constructor.
Disappear once a constructor is finished executing.
Are valid variables as long as the instance exists.
JF 3-8
World, Animation, and Game End
Constructor Example
This constructor in the World subclass uses the super()
keyword to pass the world's height, width and resolution
values to the instance.
JF 3-8
World, Animation, and Game End
Parameters Example
To change the size of the game board, modify the arguments
in the parameter of the constructor.
This example makes the world square instead of rectangular
by changing the x coordinate limit to 400.
JF 3-8
World, Animation, and Game End
JF 3-8
World, Animation, and Game End
JF 3-8
World, Animation, and Game End
JF 3-8
World, Animation, and Game End
10
GreenfootImage Class
The GreenfootImage class enables Greenfoot actors to
maintain their visible image by holding an object of type
GreenfootImage.
This class is used to help a class obtain and manipulate
different types of images.
Images that this class will use must pre-exist in the scenario's
Images folder.
JF 3-8
World, Animation, and Game End
11
new Keyword
setImage(new GreenfootImage("bee.png"));
setImage Method
GreenfootImage Class
JF 3-8
World, Animation, and Game End
12
JF 3-8
World, Animation, and Game End
13
Image from
Greenfoot class.
JF 3-8
World, Animation, and Game End
14
JF 3-8
World, Animation, and Game End
15
JF 3-8
World, Animation, and Game End
16
Variables
Use class variables to store the two image objects.
This allows the class to easily access them for use within the
instances.
A variable is declared in a class. It is used to store information for later
use, or to pass information. It can store objects or values.
Object 1
Variable 1
Object 2
Variable 2
JF 3-8
World, Animation, and Game End
17
Variable Format
A variable's format includes:
Data type: What type of data to store in the variable.
Variable name: A description of what the variable is used for so it can
be referred to later.
private variable-type
variable-name;
JF 3-8
World, Animation, and Game End
18
Declaring Variables
Declare variables before the constructors and methods.
The format for declaring a variable includes:
Keyword private to indicate that the variable is only available within
the Actor class.
Class to which the image belongs.
Placeholder for the variable into which the image will be stored.
Variables
JF 3-8
World, Animation, and Game End
19
Assignment Statements
An assignment is needed to store objects in a variable.
When an object is assigned to a variable, the variable
contains a reference to that object.
An assignment statement:
Stores the object or value into a variable.
Is written with an equals symbol.
Format:
variable = expression;
JF 3-8
World, Animation, and Game End
20
Example:
image1 = new GreenfootImage("bee.png");
image2 = new GreenfootImage("bee2.png");
JF 3-8
World, Animation, and Game End
21
JF 3-8
World, Animation, and Game End
22
JF 3-8
World, Animation, and Game End
23
JF 3-8
World, Animation, and Game End
24
JF 3-8
World, Animation, and Game End
25
Pseudocode Example
image1 is displayed when the instance is created.
When Bee makes its next movement, image2 should be
displayed, and vice versa.
This is expressed as an if-else statement.
if (current image displayed is image1) then
use image2 now
else
use image1 now
JF 3-8
World, Animation, and Game End
26
'==' Operator
The programming statements that instruct the instance to
alternate between images contains:
if-else statement
'==' operator (two equals signs)
27
JF 3-8
World, Animation, and Game End
28
JF 3-8
World, Animation, and Game End
29
JF 3-8
World, Animation, and Game End
30
JF 3-8
World, Animation, and Game End
31
Game specifications:
Create and initialize variables to store lives and score.
Provide a count of the total Flies eaten (score).
Enter the stop method to stop the game when the player's lives
reach 0.
JF 3-8
World, Animation, and Game End
32
JF 3-8
World, Animation, and Game End
33
JF 3-8
World, Animation, and Game End
34
JF 3-8
World, Animation, and Game End
35
JF 3-8
World, Animation, and Game End
36
JF 3-8
World, Animation, and Game End
37
Showing Text
Sometimes we want to keep the user of an application
informed on particular aspects of their interaction such as
lives, score or cards left.
Greenfoot again has a number of ways to achieve this.
The simplest is by using the World method showText()
JF 3-8
World, Animation, and Game End
38
JF 3-8
World, Animation, and Game End
39
Terminology
Key terms used in this lesson included:
Constructor
Defined variable
Pseudocode
JF 3-8
World, Animation, and Game End
40
Summary
In this lesson, you should have learned how to:
Construct a world object using a constructor method
Create an object using a constructor
Write programming statements to use the new keyword
Define the purpose and syntax of a variable
Recognize the syntax to define and test variables
Write programming statements to switch between two
images
Write programming statements to end a game
JF 3-8
World, Animation, and Game End
41
Java Fundamentals
3-9
Abstraction
Objectives
This lesson covers the following objectives:
Define abstraction and provide an example of when it is used
Define casting
JF 3-9
Abstraction
Abstraction
You can program a new instance to perform a single, specific
task, such as play a sound when a specific keyboard key is
pressed, or display a set of questions and answers every time
a game is started.
To create programs on a larger scale, for example one that
creates 10 objects that each perform different actions, you
need to write programming statements that let you
repeatedly create objects that perform different tasks, by just
providing the specifics for the differences.
JF 3-9
Abstraction
Abstraction Example
For example, if you are going to create 10 objects
programmatically, all placed in different locations, it is
inefficient to write 10 lines of code for each object.
Instead, you abstract the code and write more generic
statements to handle the creation and positioning of the
objects.
JF 3-9
Abstraction
Abstraction Principle
Abstraction aims to reduce duplication of information in a
program by making use of abstractions.
The abstraction principle can be a general thought such as
"don't repeat yourself."
For example, you want to create a game board that has
blocks, trees, sticks, and widgets.
You do not need to write repetitive programming statements to add
each of these items.
Instead, you can abstract the procedure to simply add objects to a
game board in a specific location.
JF 3-9
Abstraction
JF 3-9
Abstraction
JF 3-9
Abstraction
Abstraction Techniques
Abstraction occurs many ways in programming.
One technique is to abstract programming code using variables and
parameters to pass different types of information to a statement.
Another technique is to identify similar programming statements in
different parts of a program that can be implemented in just one place
by abstracting out the varying parts.
JF 3-9
Abstraction
JF 3-9
Abstraction
10
JF 3-9
Abstraction
11
JF 3-9
Abstraction
12
JF 3-9
Abstraction
13
Constructor Example
Examine the addObject() statements in the BeeWorld
constructor when adding a new Fly.
JF 3-9
Abstraction
14
JF 3-9
Abstraction
15
JF 3-9
Abstraction
16
JF 3-9
Abstraction
17
JF 3-9
Abstraction
18
JF 3-9
Abstraction
19
20
if (Greenfoot.isKeyDown("right") )
{
moveRight();
}
JF 3-9
Abstraction
21
JF 3-9
Abstraction
22
JF 3-9
Abstraction
23
24
Casting
Casting is when we want to tell the Java compiler that a class
we are accessing is really another, more specific type of class.
In our previous example we want to tell the compiler that the
World class is really a BeeWorld class.
To do this we cast it. So
World myworld = getWorld();
myworld.updateScore();
Becomes
BeeWorld myworld = (BeeWorld)getWorld();
myworld.updateScore();
JF 3-9
Abstraction
25
JF 3-9
Abstraction
26
JF 3-9
Abstraction
27
Terminology
Key terms used in this lesson included:
Abstraction
Casting
JF 3-9
Abstraction
28
Summary
In this lesson, you should have learned how to:
Define abstraction and provide an example of when it is used
Define Casting
JF 3-9
Abstraction
29
Java Fundamentals
3-10
Loops, Variables, and Arrays
Objectives
This lesson covers the following objectives:
Create a while loop in a constructor to build a world
Describe an infinite loop and how to prevent one from
occurring
Use an array to store multiple variables used to create a
world
Create an expression using logic operators
Describe the scope of a local variable in a method
JF 3-10
Loops, Variables, and Arrays
Using Loops
Writing programming statements in the World constructor is
an efficient way to create new instances with parameters
passed to them.
However, a more efficient way to create multiple instances is
to use a loop.
A loop is a statement that can execute a section of code multiple
times. There are several types of loops in Java programming.
JF 3-10
Loops, Variables, and Arrays
while Loop
The while loop executes a statement or set of statements a
number of times while a condition is true.
For example, with a while loop, you can:
Create 50 instances at once.
Execute a method 10,000 times.
Create an instance every time until the "s" key is pressed.
JF 3-10
Loops, Variables, and Arrays
JF 3-10
Loops, Variables, and Arrays
JF 3-10
Loops, Variables, and Arrays
Local Variables
A local variable is often used within loop constructs.
While it is similar to a field, it is different because:
It is declared inside the method body, not at the beginning of a class.
It cannot have a visibility modifier (public or private) in front of its
definition.
It exists only until the current method finishes running, and is then
erased from memory.
A local variable is a variable declared inside the body of the method
to temporarily store values, such as references to objects or integers.
JF 3-10
Loops, Variables, and Arrays
Example:
int i = 0;
Variable Type
(Integer)
JF 3-10
Loops, Variables, and Arrays
JF 3-10
Loops, Variables, and Arrays
10
JF 3-10
Loops, Variables, and Arrays
11
JF 3-10
Loops, Variables, and Arrays
12
This will change the variable with each loop to ensure it does
not loop indefinitely.
int i = 0;
while (i < 10)
{
addObject (new Fly (2, 90),150, 100);
i = i + 1;
}
JF 3-10
Loops, Variables, and Arrays
13
JF 3-10
Loops, Variables, and Arrays
14
JF 3-10
Loops, Variables, and Arrays
15
JF 3-10
Loops, Variables, and Arrays
16
Infinite Loops
If an end to the loop isn't established, the loop keeps
executing and never stops.
Infinite loops are a common problem in programming.
An infinite loop executes as follows:
The variable never changes.
The condition always remains true.
The loop continues looping forever.
An infinite loop is when the loop keeps executing and does not stop
because the end to the loop isn't established.
JF 3-10
Loops, Variables, and Arrays
17
Otherwise, it will rapidly switch the object it displays, and the keyboard key
will not be able to control it.
JF 3-10
Loops, Variables, and Arrays
18
JF 3-10
Loops, Variables, and Arrays
19
JF 3-10
Loops, Variables, and Arrays
20
Initialize Variables
Then initialize our class variables in the constructor.
JF 3-10
Loops, Variables, and Arrays
21
JF 3-10
Loops, Variables, and Arrays
22
Logic Operators
To test if Bee is turning when animating :
Multiple boolean expressions to express if one or both are true or false.
Logic operators to connect the boolean expressions.
For example, the statement, "When Bee is not turning and current
image is image1..." would be coded as:
if (getImage() ==
image1
&& !isTurning)
JF 3-10
Loops, Variables, and Arrays
23
Means
Definition
Exclamation Mark
(!)
NOT
AND
OR
Double ampersand
(&&)
JF 3-10
Loops, Variables, and Arrays
24
JF 3-10
Loops, Variables, and Arrays
25
Arrays
When we created our basic animation we used two images to
simulate wings flapping.
JF 3-10
Loops, Variables, and Arrays
26
Arrays
With only 4 images our code would look like this:
27
Arrays
Using an array, you can hold and access multiple variables
from just one variable.
An array is an object that holds multiple variables. An index can be
used to access the variables.
JF 3-10
Loops, Variables, and Arrays
28
JF 3-10
Loops, Variables, and Arrays
29
String[ ]
0
"Joe"
"Debbie"
"Ermal"
"Besa"
JF 3-10
Loops, Variables, and Arrays
30
JF 3-10
Loops, Variables, and Arrays
31
Array Example
In this array:
The studentnames String variable is created.
"Joe", "Debbie", "Ermal", and "Besa" are String objects that make up
the array object.
An array object is assigned to the variable studentnames.
String [] studentames;
studentnames = {"Joe", "Debbie", "Ermal", "Besa"};
JF 3-10
Loops, Variables, and Arrays
32
Element
"Joe"
"Debbie"
"Ermal"
"Besa"
JF 3-10
Loops, Variables, and Arrays
33
Element
"Joe"
"Debbie"
"Ermal"
"Besa"
JF 3-10
Loops, Variables, and Arrays
34
Array Animation
To better make an instance animate multiple images we could
declare an array.
The array includes all of the images to animate the Bee.
Declare a field in the Bee class for the array.
Iterate through the array.
JF 3-10
Loops, Variables, and Arrays
35
JF 3-10
Loops, Variables, and Arrays
36
JF 3-10
Loops, Variables, and Arrays
37
Could be written as
JF 3-10
Loops, Variables, and Arrays
38
JF 3-10
Loops, Variables, and Arrays
39
Terminology
Key terms used in this lesson included:
Array
Elements
Index
Infinite loop
Local variables
Logic operators
Loop
JF 3-10
Loops, Variables, and Arrays
40
Summary
In this lesson, you should have learned how to:
Create a while loop in a constructor to build a world
Describe an infinite loop and how to prevent one from
occurring
Use an array to store multiple variables
Create an expression using logic operators
Describe the scope of a local variable in a method
JF 3-10
Loops, Variables, and Arrays
41
Java Fundamentals
4-1
Getting Started with Eclipse
Objectives
This lesson covers the following objectives:
Identify components of Eclipse
Identify components of a Java application
Compile an application
Test to ensure application is complete
Write the code for GalToLit.java
JF 4-1
Getting Started with Eclipse
Objectives
This lesson covers the following objectives:
Modify a program to execute error free
Modify a program to use a formula to convert units of
measure
JF 4-1
Getting Started with Eclipse
JF 4-1
Getting Started with Eclipse
JF 4-1
Getting Started with Eclipse
This course assumes that you have Java and Eclipse installed
on your computer.
JF 4-1
Getting Started with Eclipse
JF 4-1
Getting Started with Eclipse
JF 4-1
Getting Started with Eclipse
JF 4-1
Getting Started with Eclipse
10
JF 4-1
Getting Started with Eclipse
11
JF 4-1
Getting Started with Eclipse
12
JF 4-1
Getting Started with Eclipse
13
The Workspace
All projects are developed and modified in a workspace.
A workspace is a collection of Projects.
In this course, you may use the same workspace for all
practice projects and packages.
A project is a way for programmers to organize Java files.
A package is how Java and Eclipse organize Java files that are
related.
Using packages will ensure that related files can find each
other.
JF 4-1
Getting Started with Eclipse
14
Switching Workspaces
You can Switch Workspaces (from the File menu) to change to
a different physical location for your files.
JF 4-1
Getting Started with Eclipse
15
JF 4-1
Getting Started with Eclipse
16
Projects in Eclipse
In Eclipse:
All programs must reside inside a project for proper compilation.
You may have one or multiple class files in one project.
One of the classes must contain a main method.
JF 4-1
Getting Started with Eclipse
17
JF 4-1
Getting Started with Eclipse
18
Project Display
The project is created and displayed as a folder.
It displays in the Package view to the left of the edit area.
JF 4-1
Getting Started with Eclipse
19
JF 4-1
Getting Started with Eclipse
20
Naming Packages
Name this package the same name as the Project using lower
camel case.
Camel case is the practice of stringingCapitalizedWords together with
no spaces. Lower camel case does not capitalize the lead word.
JF 4-1
Getting Started with Eclipse
21
Right click on the project name to create a new class named StudyPage
in the studyTool package.
2.
JF 4-1
Getting Started with Eclipse
22
JF 4-1
Getting Started with Eclipse
23
New Class
Notice the following:
The StudyPage.java class appears in the studyTool package in the
Package Explorer View.
The StudyPage.java class is created with the main method.
JF 4-1
Getting Started with Eclipse
24
JF 4-1
Getting Started with Eclipse
25
JF 4-1
Getting Started with Eclipse
26
System.out.println(termvar + ":
" + termdef);
JF 4-1
Getting Started with Eclipse
27
JF 4-1
Getting Started with Eclipse
28
JF 4-1
Getting Started with Eclipse
29
JF 4-1
Getting Started with Eclipse
30
JF 4-1
Getting Started with Eclipse
31
JF 4-1
Getting Started with Eclipse
32
Terminology
Key terms used in this lesson included:
Camel case
Eclipse: edit and view areas, perspective, workspace
Java JRE vs. Java JDK
Java classes
Java packages
Java main methods
JF 4-1
Getting Started with Eclipse
33
Summary
In this lesson, you should have learned how to:
Identify components of Eclipse
Identify components of a Java application
Compile an application
Test to ensure application is complete
Write the code for GalToLit.java
JF 4-1
Getting Started with Eclipse
34
Summary
In this lesson, you should have learned how to:
Modify a program to execute error free
Modify a program to use a formula to convert units of
measure
JF 4-1
Getting Started with Eclipse
35
Java Fundamentals
4-2
Object and Driver Classes
Objectives
This lesson covers the following objectives:
Describe the general form of a Java program
Describe the difference between an Object class and a Driver
class
Access a minimum of two Java class APIs
Explain and give examples of Java keywords
Create an Object class
Create a Driver class
JF 4-2
Object and Driver Classes
JF 4-2
Object and Driver Classes
Driver Classes
Driver classes:
Contain a main method.
A main method is necessary to run a Java program in Eclipse.
The main method may include:
Instances of objects from an object class
Variables
Loops, conditional statements (if-else)
Other programming logic
JF 4-2
Object and Driver Classes
Object Classes
Object classes:
Are classes that define objects to be used in a driver class.
Can be found in the Java API, or created by you.
Examples: String, BankAccount, Student, Rectangle
The Java API is a library of packages and object classes that are
already written and are available for use in your programs.
JF 4-2
Object and Driver Classes
Packages
Classes
JF 4-2
Object and Driver Classes
JF 4-2
Object and Driver Classes
JF 4-2
Object and Driver Classes
Description
charAt(int index)
length()
substring(int beginIndex)
JF 4-2
Object and Driver Classes
10
11
JF 4-2
Object and Driver Classes
12
<package_name>;
import <other_packages>;
public class ClassName
{
<variables (also known as fields)>;
<constructor method(s)>;
<other methods>;
}
JF 4-2
Object and Driver Classes
13
Key Terms
Term
Definition
package keyword
Defines where this class lives relative to other classes, and provides a
level of access control.
Use access modifiers (such as public and private) to control access.
import keyword
Defines other classes or groups of classes that you are using in your
class.
The import statement provides the compiler information that identifies
outside classes used within the current class.
Precedes the name of the class.
class keyword
class variables or
instance fields
(often shortened to
fields)
The name of the class and the file name must match when the class is
declared public (which is a good practice). However, the keyword
public in front of the class keyword is a modifier and is not required.
JF 4-2
Object and Driver Classes
14
Key Terms
Term
Definition
Constructors
Methods
JF 4-2
Object and Driver Classes
15
Java Keywords
All Java programs use Java keywords.
Examples include the following words: class, public, String,
int, for, while, and double.
The font color for Keywords will change in the Eclipse editor.
List of Java keywords:
http://docs.oracle.com/javase/tutorial/java/nutsandbolts/_keywords.html
JF 4-2
Object and Driver Classes
16
JF 4-2
Object and Driver Classes
17
Camel Case
Camel case is the practice of stringing capitalized words
together with no spaces.
Lower camel case strings capitalized words together but the
lead word is not capitalized.
For example: thisIsLowerCamelCase.
Upper camel case strings capitalized words together, but the
lead word is capitalized.
For example: ThisIsUpperCamelCase.
JF 4-2
Object and Driver Classes
18
JF 4-2
Object and Driver Classes
19
JF 4-2
Object and Driver Classes
20
JF 4-2
Object and Driver Classes
21
22
Import Keyword
The import keyword is used to identify packages or object
classes that you want to use in your class.
You can import a single class or an entire package.
You can include multiple import statements.
Import statements follow the package declaration and
precede the class declaration.
import java.util.Scanner;
JF 4-2
Object and Driver Classes
23
Import Statements
An import statement is not required, and by default, your
class always imports java.lang from the API.
http://docs.oracle.com/javase/7/docs/api/java/lang/Package.html
JF 4-2
Object and Driver Classes
24
import java.util.*;
import java.util.Date;
import java.util.Calendar;
JF 4-2
Object and Driver Classes
25
JF 4-2
Object and Driver Classes
26
Access Modifier
JF 4-2
Object and Driver Classes
27
JF 4-2
Object and Driver Classes
28
JF 4-2
Object and Driver Classes
29
JF 4-2
Object and Driver Classes
30
Constructor Methods
A constructor method is unique in Java because:
The method creates an instance of the class.
Constructors always have the same name as the class and do not
declare a return type.
All code for this method must be
enclosed in a set of curly brackets { }.
public Student{}
JF 4-2
Object and Driver Classes
31
Constructor Methods
With constructor methods:
You can declare more than one constructor in a class declaration.
You do not have to declare a constructor, in fact, Java will provide a
default (blank) constructor for you.
If you declare one or more constructors, Java will not provide a default
constructor.
All code for this method must be
enclosed in a set of curly brackets { }.
public Student{}
JF 4-2
Object and Driver Classes
32
public Student(){
}
JF 4-2
Object and Driver Classes
33
JF 4-2
Object and Driver Classes
No parameters
34
JF 4-2
Object and Driver Classes
35
JF 4-2
Object and Driver Classes
Constructor
36
JF 4-2
Object and Driver Classes
37
Constructors
A constructor is a method that creates an object.
In Java, constructors are methods with the same name as
their class used to create an instance of an object.
Constructors are invoked using the new keyword.
Example of code that could be used in a Driver Class to create
an object from the Student constructor:
Student stu = new Student();
JF 4-2
Object and Driver Classes
38
Main Method
To run a Java program you must define a main method in a
Driver Class.
The main method is automatically called when the class is
called.
Remember to name the file the same as the class.
JF 4-2
Object and Driver Classes
39
JF 4-2
Object and Driver Classes
40
JF 4-2
Object and Driver Classes
41
42
JF 4-2
Object and Driver Classes
43
JF 4-2
Object and Driver Classes
44
Add a toString() method to the Student class that will allow us to see
the Student data as output.
JF 4-2
Object and Driver Classes
45
JF 4-2
Object and Driver Classes
46
JF 4-2
Object and Driver Classes
47
JF 4-2
Object and Driver Classes
48
49
Code Blocks
A code block is defined by opening and closing "curly braces"
{ }. When examining code blocks, consider the following:
Every class declaration is enclosed in a code block.
Method declarations, including the main method, are enclosed in code
blocks.
Java fields and methods have block (or class) scope.
public class SayHello
{
JF 4-2
Object and Driver Classes
50
Classes
Methods
Conditionals (if statements, switch statements)
Loops
JF 4-2
Object and Driver Classes
51
Terminology
Key terms used in this lesson included:
Access modifiers
Code blocks
Constants
Constructors
Driver class
JF 4-2
Object and Driver Classes
52
Terminology
Key terms used in this lesson included:
import statements
Java API
Java comments
Java keywords
Lower camel case
Methods
JF 4-2
Object and Driver Classes
53
Terminology
Key terms used in this lesson included:
Object class
Packages
Parameters
Programmer-created class
Upper camel case
Variables
JF 4-2
Object and Driver Classes
54
Summary
In this lesson, you should have learned how to:
Describe the general form of a Java program
Describe the difference between an Object class and a Driver
class
Access a minimum of two Java class APIs
Explain and give examples of Java keywords
Create an Object class
Create a Driver class
JF 4-2
Object and Driver Classes
55
Java Fundamentals
4-3
Data Types and Operators
Objectives
This lesson covers the following objectives:
Use primitive data types in Java code
Specify literals for the primitive types and for Strings
Demonstrate how to initialize variables
Describe the scope rules of a method
Recognize when an expression requires a type conversion
JF 4-3
Data Types and Operators
Overview
This lesson covers the following topics:
Apply casting in Java code
Use arithmetic operators
Use the assignment operator
Use a method from the Math class
Access a Math class method from the Java API
JF 4-3
Data Types and Operators
Are used to define the kind of data that can be stored inside a variable.
Ensure that only correct data is stored.
Are either declared or inferred.
Can be created by the programmer.
JF 4-3
Data Types and Operators
JF 4-3
Data Types and Operators
JF 4-3
Data Types and Operators
Size
Example Data
Data Description
boolean
1 bit
true, false
byte
1 byte
(8 bits)
12, 128
char
2 bytes
short
2 bytes
6, -14, 2345
JF 4-3
Data Types and Operators
long
float
double
Size
Example Data
4 bytes
8 bytes
4 bytes
8 bytes
6, -14, 2345
Data Description
Stores integers from:
-2,147,483,648 to 2,147,483,647
3459111, 2
3.145, .077
.0000456, 3.7
JF 4-3
Data Types and Operators
JF 4-3
Data Types and Operators
10
JF 4-3
Data Types and Operators
11
JF 4-3
Data Types and Operators
12
JF 4-3
Data Types and Operators
13
JF 4-3
Data Types and Operators
14
JF 4-3
Data Types and Operators
15
Casting Example
This is an example of
casting. In this example,
the binary
value is cast to a byte
type.
JF 4-3
Data Types and Operators
16
JF 4-3
Data Types and Operators
17
If a variable name consists of one word, spell that word in all lowercase
letters.
If a variable name consists of more than one word, use
lowerCamelCase.
JF 4-3
Data Types and Operators
18
JF 4-3
Data Types and Operators
19
Variable Scope
Scope is used to describe the block of code where a variable
exists in a program.
It is possible for multiple variables with the same name to
exist in a Java program.
In most cases, the innermost variable has precedence.
JF 4-3
Data Types and Operators
20
JF 4-3
Data Types and Operators
21
JF 4-3
Data Types and Operators
22
23
24
Arithmetic Operators
Java has several arithmetic operators to perform
math operations.
Symbol
Operator Description
Addition operator
Subtraction operator
Multiplication operator
++
--
JF 4-3
Data Types and Operators
25
JF 4-3
Data Types and Operators
26
JF 4-3
Data Types and Operators
27
//x is equal to 4
z = ++x;
Post-increment notation:
int x = 3;
x++;
//x is equal to 4
z = x++;
JF 4-3
Data Types and Operators
28
Assignment Operator
Java uses the = (equal sign) as the assignment operator. The
evaluation of the expression on the right is assigned to the
memory location on the left.
int x = 4;
int y = 5;
int z = 10;
int total = 12;
X
Total
10
12
JF 4-3
Data Types and Operators
29
Total
10
54
JF 4-3
Data Types and Operators
30
Total
10
??
JF 4-3
Data Types and Operators
31
Total
10
34
JF 4-3
Data Types and Operators
32
JF 4-3
Data Types and Operators
33
5
3
16
15
1
quotient
Quotient
dividend
Dividend
Remainder
34
JF 4-3
Data Types and Operators
35
JF 4-3
Data Types and Operators
36
Make one of the literal integers into a literal double so that Java will
always use a double and an integer and will implicitly convert the
answer to a double, not truncate.
double volume = 1 / 3.0 * 3.14 * radius * radius * height;
JF 4-3
Data Types and Operators
37
JF 4-3
Data Types and Operators
38
JF 4-3
Data Types and Operators
39
JF 4-3
Data Types and Operators
40
JF 4-3
Data Types and Operators
41
JF 4-3
Data Types and Operators
42
JF 4-3
Data Types and Operators
43
JF 4-3
Data Types and Operators
44
double
Implicit
conversion
double
d1
JF 4-3
Data Types and Operators
int
5;
45
int
Explicit
conversion
required
JF 4-3
Data Types and Operators
double
int x
(int)12.95;
46
JF 4-3
Data Types and Operators
47
JF 4-3
Data Types and Operators
48
JF 4-3
Data Types and Operators
49
Classes
JF 4-3
Data Types and Operators
50
Math Class
Find the Math Class in the class frame window.
Scroll to see a
list of fields and methods
available in this class.
JF 4-3
Data Types and Operators
51
PI Field
Scroll to find the PI field.
To use PI in a program, specify the class name (Math) and PI
separated by the dot operator.
For example, this field would yield a more accurate volume
calculation in our earlier example if it is used as follows:
double volume = (double) 1 / 3 * Math.PI * radius * radius * height;
JF 4-3
Data Types and Operators
52
To calculate the square root of 625, use the class name and
the method separated again by the dot operator.
double answer = Math.sqrt(625);
JF 4-3
Data Types and Operators
53
JF 4-3
Data Types and Operators
54
JF 4-3
Data Types and Operators
55
Terminology
Key terms used in this lesson included:
Arithmetic operator
Assignment operator
boolean
char
Conventions
Declaration
double
JF 4-3
Data Types and Operators
56
Terminology
Key terms used in this lesson included:
float
Initialization
int
Literals
long
Order of Operation
Primitive data types
JF 4-3
Data Types and Operators
57
Terminology
Key terms used in this lesson included:
Scope
Short
Truncation
Type casting
Type conversion
Variables
JF 4-3
Data Types and Operators
58
Summary
In this lesson, you should have learned how to:
Use primitive data types in Java code
Specify literals for the primitive types and for Strings
Demonstrate how to initialize variables
Describe the scope rules of a method
Recognize when an expression requires a type conversion
JF 4-3
Data Types and Operators
59
Summary
In this lesson, you should have learned how to:
Apply casting in Java code
Use arithmetic operators
Use the assignment operator
Use a method from the Math class
Access a Math class method from the Java API
JF 4-3
Data Types and Operators
60
Java Fundamentals
4-4
Strings
Objectives
This lesson covers the following objectives:
Instantiate (create) a String
Describe what happens when a String is modified
Use the + and += operators for concatenating Strings
Interpret escape sequences in String literals
JF 4-4
Strings
Overview
This lesson covers the following topics:
Recognize the difference between a String and a primitive
char data type
Test Strings with the compareTo() and equals() method
Describe why the == operator does not always work when
testing String equality
Use String methods length(), substring(), indexOf(), and
charAt()
JF 4-4
Strings
What is a String?
A String is an object that contains a sequence of characters.
Declaring and instantiating a String is much like any other
object variable.
However, there are differences:
They can be instantiated (created) without using the new keyword.
They are immutable.
Once instantiated, they are final and cannot be changed.
JF 4-4
Strings
Modifying a String
Attempting to modify a String does not modify it, it creates a
new String object.
As a new programmer, you will not notice this difference.
However, it becomes important in real systems where
processing time is a key element in program design.
JF 4-4
Strings
JF 4-4
Strings
Class Template
Use the following class to insert examples from this section.
import java.util.Scanner;
public class StringPractice{
public static void main(String[] args){
//paste practice code here
}
JF 4-4
Strings
Instantiating a String
Strings are object reference types.
They can be instantiated in two ways:
JF 4-4
Strings
String References
When you create a reference to an Object or String, the
object does not necessarily exist yet.
In the code below, since name is not initialized, the program
will not compile.
The variable name is a null pointer.
String name;
System.out.println("My name is " + name);
Name = null
JF 4-4
Strings
10
String References
In this code, one String object exists and name is referencing
it. The reference name2 is null.
How will this line change memory?
String name,name2;
name = "Mya";
name2 = null
name = Mya
name2 = name;
name
name2
Mya
name
name2
Mya
JF 4-4
Strings
11
String References
Executing this line of code changes the name2 reference.
name2 = name;
name
JF 4-4
Strings
name2
12
String References
Executing these lines of code creates two instances of the
String Mya in memory.
String name, name2;
name = "Mya";
name2 = "Mya";
Here the JVM compiler decides to save space and stores only
one String Object that holds the String Mya.
String Object
name
JF 4-4
Strings
Mya
name2
13
String References
If we run a very similar program but ask the user to enter
Strings, we get a different result.
Scanner in= new Scanner(System.in);
String name, name2;
name=in.next();
name2=in.next();
If the user types Mya for both Strings, the compiler actually
creates two different String Objects.
String Object
String Object
Mya
Mya
name
JF 4-4
Strings
name2
14
String References
It is very difficult to predict when Java will create a new String
or use an existing object for a String that is identical to the
new String.
JF 4-4
Strings
15
String Concatenation
Concatenate two strings together with the + and +=
operators.
Symbol + is used to concatenate two strings together.
Symbol += is used to concatenate two strings together and
assign it to itself all in one operation.
String
String
String
String
String
s1
s2
s3
s4
s1
= "This is a ";
= "string";
= s1 + s2;
= "This is a " + s2;
+= s2;
16
Manipulation of Strings
Each time a String is changed, a new String is created in a new
memory location and the reference is moved to the new
location.
Some Strings will point to the same reference object in
memory.
Making a modification to one String that is pointing to the
shared reference will not make a modification to the others.
The one that you modify points to the new memory address
that holds the new/modified string and the others still point
to the original one.
JF 4-4
Strings
17
18
Escape Sequences
Escape sequences in string literals allow the user to add
characters that would be misinterpreted by the compiler.
For example, to include a double-quote in your String, the
compiler would interpret the double-quote as the beginning
or ending of your String rather than including it.
Use the escape sequence \" to include a double-quote.
String s1 = "This is an example of an escape.
\n And now we're on a new line. \n \t This is a tab."
String s2 = "\"This is a quote \"";
System.out.println(s1);
System.out.println(s2);
JF 4-4
Strings
19
Representation
Alternate Octal
Escape
Representation
\"
Double quote
\u0022
\'
Single quote
\u0027
\\
Backslash
\u005c
\t
Horizontal tab
\u0009
\n
Line feed
\u000a
\b
Backspace
\u0008
\r
Carriage return
\u000d
\f
Form feed
\u000c
Octal Escape
Octal value
\u0000 to \u00ff
JF 4-4
Strings
20
compareTo() Method
Methods to use when comparing Strings.
Method: s1.compareTo(s2)
Should be used when trying to find the lexicographical order of two
strings.
Returns an integer.
If s1 is less than s2, an int < 0 is returned.
If s1 is equal to s2, 0 is returned.
If s1 is larger than s2, an int > 0 is returned.
JF 4-4
Strings
21
equals() Method
Methods to use when comparing Strings.
Method: s1.equals(s2)
Should be used when you only wish to find if the two strings are equal.
Returns a boolean value.
If true is returned, s1 is equal to s2.
If false is returned, s1 is not equal to s2.
JF 4-4
Strings
22
JF 4-4
Strings
23
JF 4-4
Strings
24
s1
s2
s3
s4
=
=
=
=
"This is a String.";
new String("This is a String.");
"String.";
"This is a " + s3;
System.out.println(s1 == s2);
System.out.println(s1 == s4);
JF 4-4
Strings
25
s1
s2
s3
s4
s5
=
=
=
=
=
"This is a String.";
"This is a String.";
"This is ";
"a String.";
s3 + s4;
System.out.println(s1 == s2);
System.out.println(s1 == s5);
JF 4-4
Strings
26
JF 4-4
Strings
27
JF 4-4
Strings
28
JF 4-4
Strings
29
s3.indexOf(char c);
s4.charAt(int index);
Returns the character of the String located at the index passed as the
parameter.
Index can be an integer from 0 to s4.length()-1.
JF 4-4
Strings
30
JF 4-4
Strings
31
Terminology
Key terms used in this lesson included:
Concatenation
Escape sequences
Instantiate
Reference object
String object
String methods compareTo() and equals()
JF 4-4
Strings
32
Summary
In this lesson, you should have learned how to:
Instantiate (create) a String
Describe what happens when a String is modified
Use the + and += operators for concatenating Strings
Interpret escape sequences in String literals
JF 4-4
Strings
33
Summary
In this lesson, you should have learned how to:
Recognize the difference between a String and a primitive
char data type
Test Strings with the compareTo() and equals() method
Describe why the == operator does not always work when
testing String equality
Use String methods length(), substring(), indexOf(), and
charAt()
JF 4-4
Strings
34
Java Fundamentals
5-1:
Scanner and Conditional Statements
Objectives
This lesson covers the following objectives:
Use Scanner for user input during program execution
Use if-else logic and statements
Apply switch logic and statements in Java code
Use break and default effectively in a switch statement
Use the ternary operator
JF 5-1
Scanner and Conditional Statements
Prompting the user can be done with simple code that will
appear in the console screen where the user can then enter
their input.
System.out.println("Write instructions for user here.");
JF 5-1
Scanner and Conditional Statements
Scanner
To read in the input that the user has entered, use the Java
object Scanner.
To initialize a Scanner, write:
JF 5-1
Scanner and Conditional Statements
Why Scanner?
Scanner makes it easy to read in the user's input because it
already has methods that do this very task.
The Scanner method next() reads in the user's input as a
String and returns that String. This line of code:
Creates a new string called input.
Scans in the string that the user has entered into the output
console using the scanner called in.
Sets input equal to the string that was read in by the scanner.
String input = in.next();
JF 5-1
Scanner and Conditional Statements
JF 5-1
Scanner and Conditional Statements
What It Does
When to Use
nextInt()
hasNext()
close()
JF 5-1
Scanner and Conditional Statements
Relational Operators
Java has six relational operators used to test primitive or
literal numerical values. Relational operators are used to
evaluate if-else and loop conditions.
Relational Operator
Definition
>
Greater than
>=
==
Equal to
<
Less than
<=
!=
Not equal to
JF 5-1
Scanner and Conditional Statements
JF 5-1
Scanner and Conditional Statements
10
JF 5-1
Scanner and Conditional Statements
11
Logic Operators
Java has three logic operators used to combine boolean
expressions into complex tests.
Logic Operator
Meaning
&&
AND
||
OR
NOT
JF 5-1
Scanner and Conditional Statements
12
JF 5-1
Scanner and Conditional Statements
13
JF 5-1
Scanner and Conditional Statements
14
JF 5-1
Scanner and Conditional Statements
15
JF 5-1
Scanner and Conditional Statements
16
JF 5-1
Scanner and Conditional Statements
17
18
JF 5-1
Scanner and Conditional Statements
19
if-else Statements
with the String Data Type
import java.util.Scanner;
public class StringChecker{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
String name = "";
System.out.println("Enter your name:");
name = in.next();
if( name.equals("Elvis"))
System.out.println("You are the king of rock and roll");
else if( name.equals("Michael Jackson"))
System.out.println("You are the king of pop!");
else
System.out.println("You are not the king");
}
}
JF 5-1
Scanner and Conditional Statements
20
Switch Statement
Like the if-else example earlier, consider a program that takes
two integer inputs from a user and performs a specified
mathematical operation.
To support different operators a test is needed to see if the
input was any of the following:
* / + - %
JF 5-1
Scanner and Conditional Statements
21
JF 5-1
Scanner and Conditional Statements
22
JF 5-1
Scanner and Conditional Statements
23
JF 5-1
Scanner and Conditional Statements
24
JF 5-1
Scanner and Conditional Statements
25
System.out.println("You
System.out.println("You
System.out.println("You
System.out.println("You
System.out.println("You
System.out.println("You
win
win
win
win
win
win
$1000");
a Samsung Galaxy III-S");
Laptop");
iPod");
Stapler");
Staple Remover");
System.out.println("No Gift");
JF 5-1
Scanner and Conditional Statements
26
JF 5-1
Scanner and Conditional Statements
27
JF 5-1
Scanner and Conditional Statements
28
JF 5-1
Scanner and Conditional Statements
29
Ternary Operator
The ternary operator (?:) in Java is used to create a shorter
version of an if-else statement.
In the following example, there are three parameters using
this operator.
The first is the boolean test (c>9).
The second (6) is the value to return if the test is true.
The third (7) is the value to return if the test is false. It is
often used as part of an assignment.
int x = c > 9 ? 6 : 7;
JF 5-1
Scanner and Conditional Statements
30
JF 5-1
Scanner and Conditional Statements
31
Terminology
Key terms used in this lesson included:
if statements
If-else statements
Scanner
switch statements (case, switch, and default)
Ternary operators
JF 5-1
Scanner and Conditional Statements
32
Summary
In this lesson, you should have learned how to:
Use Scanner for user input during program execution
Use if-else logic and statements
Apply switch logic and statements in Java code
Use break and default effectively in a switch statement
Use the ternary operator
JF 5-1
Scanner and Conditional Statements
33
Java Fundamentals
5-2
Control Statements
Objectives
This lesson covers the following objectives:
Create a while loop
Create a do-while loop
Create a for loop
JF 5-2
Control Statements
What is a Loop?
Many everyday tasks involve doing an action,
and then repeating the same procedure or
action on a different object.
When folding clean clothes, there are three
basic steps:
Pick up the piece of clothing.
Fold it.
Put it away.
Loops
In programming, there are times when you want to work with
multiple inputs, but you want to execute the same logic for
each input item.
A loop allows you to have a series of inputs with the same
code.
Loops will start at the beginning of a piece of code, execute
the logic you wish, and then return to the beginning of the
loop with new input, ready to execute the code once more.
JF 5-2
Control Statements
While this is fairly simple code, using a loop will simplify the
code further.
loop (loop condition){
input currentNumber
sum = sum + currentNumber;
}end loop
JF 5-2
Control Statements
JF 5-2
Control Statements
Stopping Conditions
A loop needs a stopping condition, which could be specified
as:
A set number of times to run the code.
A boolean condition that is changed in the code to make the loop stop
executing.
JF 5-2
Control Statements
Types of Loops
Java has three basic types of loops that work with these two
types of stopping conditions:
while loops
for loops
do-while loop
Post-test loop: The condition is
tested after the each execution of
the loop. If the condition is false,
the loop will still execute at least
once, but will stop at the end of
the loop.
JF 5-2
Control Statements
JF 5-2
Control Statements
10
Infinite Loops
If you do not allow for a change in the condition, the loop will
run forever as an infinite loop.
JF 5-2
Control Statements
11
12
13
JF 5-2
Control Statements
14
JF 5-2
Control Statements
15
If you do not allow for a change in the condition, the loop will
run forever as an infinite loop.
JF 5-2
Control Statements
16
JF 5-2
Control Statements
17
JF 5-2
Control Statements
18
JF 5-2
Control Statements
19
insect.fly();
} while(noFlowerFound)
insect.land();
JF 5-2
Control Statements
//Step 1
//Step 2
//Final Step
20
JF 5-2
Control Statements
21
JF 5-2
Control Statements
22
JF 5-2
Control Statements
23
JF 5-2
Control Statements
24
JF 5-2
Control Statements
25
JF 5-2
Control Statements
26
JF 5-2
Control Statements
27
When to Use
while
do-while
for
JF 5-2
Control Statements
28
JF 5-2
Control Statements
29
JF 5-2
Control Statements
30
break Example
This example will ask for to input a number ten times.
If the user enters the value 999, the loop will terminate
regardless of the value of i (the lcv).
import java.util.Scanner;
public class BreakExample{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int numInputs = 10, input = 0, sum = 0, stopLoop = 999;
for(int i = 0; i < numInputs; i++){
input = in.nextInt();
//user inputs a number
if(input==stopLoop)
//if the number is 999, exit the loop without adding to the sum
break;
else
sum+=input;
//if the number is not 999, add it to the sum
}
System.out.println("The sum of the numbers entered is: " + sum);
}
}
JF 5-2
Control Statements
31
continue Example
Given a list of integers (you want to output a message for all
the odd numbers, and you want to skip over the even
numbers), this can be done using the following code.
import java.util.Scanner;
public class ContinueExample{
public static void main(String[] args){
Scanner in = new Scanner(System.in);
int numInputs = 10, input = 0;
for(int i = 0; i < numInputs; i++){
//user inputs a number
input = in.nextInt();
if(input % 2 == 0)
//if it's even
continue; //skip the remaining code in the loop, increment i, re-check the
System.out.println("That number was odd"); //output only if odd
}
}
}
JF 5-2
Control Statements
condition
32
JF 5-2
Control Statements
33
Terminology
Key terms used in this lesson included:
break
continue
do-while loop
for loop
while loop
JF 5-2
Control Statements
34
Summary
In this lesson, you should have learned how to:
Create a while loop
Create a do-while loop
Create a for loop
JF 5-2
Control Statements
35
Java Fundamentals
6-1
Arrays
Objectives
This lesson covers the following objectives:
Write a single-dimensional array in a Java program using
primitive data types
Write a single-dimensional array in a Java program using
reference (Object) types
Write a 2-dimensional array in a Java program using primitive
data types
Write a 2-dimensional array in a Java program using reference
(Object) types
Declare an array, initialize an array, and traverse the array
JF 6-1
Arrays
Overview
This lesson covers the following topics:
Describe array initialization
Distinguish between the String method length() and an
array's length value
Rewrite a Java program to store integers into an array,
perform a mathematical calculation, and display the result
Use alternative array declaration syntax
JF 6-1
Arrays
What is an Array?
An array is a collection of values of the same data type stored
in a container object.
Can be any number of values.
Length of the array is set when the array is declared.
Size is fixed once the array is declared.
JF 6-1
Arrays
Array Elements
Every value is called an element
Each element is accessed by an index.
Index must be an integer.
Index always starts at 0.
JF 6-1
Arrays
JF 6-1
Arrays
Declaring an Array
There are three parts to declaring an array:
Data type
Variable name
Array size
JF 6-1
Arrays
JF 6-1
Arrays
JF 6-1
Arrays
10
String[] myBouquet;
myBouquet = new String[6];
String[] myBouquet = new String[6];
Array name is
myBouquet.
JF 6-1
Arrays
11
Data Type
Name
Size
JF 6-1
Arrays
12
JF 6-1
Arrays
Alternate syntax:
int primeNumbers[];
int evenNumbers[];
double prices[][];
String words[];
Point coordinates[];
Rectangle blocks[][];
13
JF 6-1
Arrays
Alternate syntax:
int primeNumbers[];
int evenNumbers[];
double prices[][];
String words[];
Point coordinates[];
Rectangle blocks[][];
14
Initializing an Array
Once you declare an array, you must initialize it to set the
values for specified indexes.
There are three components to initializing an array:
Variable name
Index
Value
JF 6-1
Arrays
15
JF 6-1
Arrays
16
Variable Name
Index
JF 6-1
Arrays
//previous declaration
//Store "Rose" as the first element
//Store "Sunflower" as the second
//and so on
//"Lily" is the last (sixth) element
Value
17
Value:
Rose
Sunflower
Daisy
Dandelion
Violet
Lily
JF 6-1
Arrays
18
Notice that using this method does not specify size, but it is
assigned a size based on the number of elements in the list
between the {}.
JF 6-1
Arrays
19
JF 6-1
Arrays
20
JF 6-1
Arrays
21
JF 6-1
Arrays
22
Array Representation
When arrays are declared but not yet initialized, the elements
are given the default value associated with the data type.
For example, the default for numeric data types, such as int,
is 0. The default for Object types, such as String is "" (null).
When the array is declared, the representation in the table is
as follows.
int[] myArray = new int[5];
Index:
Value:
JF 6-1
Arrays
23
Index:
Value:
32
27
JF 6-1
Arrays
24
JF 6-1
Arrays
25
JF 6-1
Arrays
26
27
JF 6-1
Arrays
28
JF 6-1
Arrays
29
for-each Loop
Java offers a for-each loop, an alternative to using the
initialized counter to iterate through an array.
When used to access the elements of an array, the for- each
loop works the same way as the for loop, but is implemented
in a simpler way.
If we replace the for loop code from our previous example
with the following code, we get the same result.
//remember that the index range is 0 to 5 for an array //of size 6
for (String myFlower : myBouquet)
{
System.out.println(myFlower);
}
JF 6-1
Arrays
30
for-each Loop
The for-each loop accesses and (one-at-a-time) returns all
elements of an array.
Changes to the array elements cannot be made using a for each loop.If we replace the for loop code from our previous
example with the following code, we get the same result.
The example below will print the length of each string in the
array myBouquet.
//remember that the index range is 0 to 5 for an array //of size 6
for (String myFlower : myBouquet)
{
System.out.println(myFlower);
}
JF 6-1
Arrays
31
JF 6-1
Arrays
32
JF 6-1
Arrays
33
Two-Dimensional Arrays
A two-dimensional array, called an "array of arrays," is an
array that stores other arrays.
The number of arrays contained within the array is defined
upon declaration.
The number of items in each internal array is also defined
upon declaration.
JF 6-1
Arrays
34
JF 6-1
Arrays
35
JF 6-1
Arrays
36
JF 6-1
Arrays
37
JF 6-1
Arrays
38
JF 6-1
Arrays
39
JF 6-1
Arrays
40
JF 6-1
Arrays
41
= new int[3][2];
7;
24;
352;
2;
37;
65;
Method 2:
int[][] myArray = new int[][] {{7, 24}, {352, 2}, {37, 65}};
JF 6-1
Arrays
42
JF 6-1
Arrays
43
0 (Rose)
Red
Peach
Yellow
1 (Sunflower)
Yellow
White
Blue
2 (Daisy)
Green
Blue
Purple
3 (Dandelion)
White
White
White
4 (Violet)
Purple
Pink
Violet
5 (Lily)
Pink
Orange
White
JF 6-1
Arrays
44
JF 6-1
Arrays
45
JF 6-1
Arrays
46
JF 6-1
Arrays
47
JF 6-1
Arrays
48
Solution:
Peach Rose
White Lilly
JF 6-1
Arrays
49
JF 6-1
Arrays
50
JF 6-1
Arrays
51
JF 6-1
Arrays
52
two.length == 3;
is FALSE
four[0].length == 5;
JF 6-1
Arrays
53
JF 6-1
Arrays
54
JF 6-1
Arrays
55
JF 6-1
Arrays
56
JF 6-1
Arrays
57
JF 6-1
Arrays
58
JF 6-1
Arrays
59
JF 6-1
Arrays
60
JF 6-1
Arrays
61
JF 6-1
Arrays
62
JF 6-1
Arrays
63
JF 6-1
Arrays
64
JF 6-1
Arrays
65
Terminology
Key terms used in this lesson included:
Algorithm
Array
Array of arrays
Command-line argument
Index
Iterate
JF 6-1
Arrays
66
Terminology
Key terms used in this lesson included:
Nested for loop
Single-dimensional array
Traverse
Two-dimensional array
JF 6-1
Arrays
67
Summary
In this lesson, you should have learned how to:
Write a single-dimensional array in a Java program using
primitive data types
Write a single-dimensional array in a Java program using
reference (Object) types
Write a 2-dimensional array in a Java program using primitive
data types
Write a 2-dimensional array in a Java program using reference
(Object) types
Declare an array, initialize an array, and traverse the array
JF 6-1
Arrays
68
Summary
In this lesson, you should have learned how to:
Describe array initialization
Distinguish between the String method length() and an
array's length value
Rewrite a Java program to store integers into an array,
perform a mathematical calculation, and display the result
Use alternative array declaration syntax
JF 6-1
Arrays
69
Java Fundamentals
6-2
Handling Errors
Objectives
This lesson covers the following objectives:
Describe the different kinds of errors that can occur and how
they are handled in Java
Describe what exceptions are used for in Java
Determine what exceptions are thrown for any foundation
class
Write code to handle an exception thrown by the method of a
foundation class
JF 6-2
Handling Errors
Types of Errors
An error indicates that a there is a problem with interpreting
your program.
There are three types of errors:
Syntax errors
Logic errors
Exceptions (run-time errors)
JF 6-2
Handling Errors
Syntax Errors
An error can occur when a file is compiled. These errors are
coding or syntax errors, such as:
Missing semicolons
Spelling errors
Assigning a value to a variable that is not the correct type
JF 6-2
Handling Errors
Incorrect
if(x==y){
Correct
JF 6-2
Handling Errors
JF 6-2
Handling Errors
Logic Errors
Logic errors occur as a result of programmer logic that is
incorrect.
These errors do not produce a compile or runtime error.
For example, a loop runs too many times, or the program
produces incorrect output.
JF 6-2
Handling Errors
Logic Errors
Placing a semicolon after an if condition or initializing a loop:
Interpreters read the semicolon as the end of the loop, which means
that everything after the semicolon will be treated as outside of the
loop.
for(int i = 0; i < 5; i++);
System.out.println(i);
JF 6-2
Handling Errors
This statement
will only execute
once. Why?
JF 6-2
Handling Errors
10
Exceptions
Once a file compiles successfully, an error can occur when a
file is tested during runtime.
These runtime errors are called exceptions and should be
handled by the programmer using code in the program,
otherwise known as "throwing" the exception.
JF 6-2
Handling Errors
11
JF 6-2
Handling Errors
12
JF 6-2
Handling Errors
13
Unchecked Exceptions
It is optional to handle unchecked exceptions in Java.
However, if the unchecked exception is not handled, and an
error occurs, the program will crash.
Common unchecked exceptions:
Index out of bounds exception
Null pointer exception
JF 6-2
Handling Errors
14
JF 6-2
Handling Errors
15
JF 6-2
Handling Errors
16
JF 6-2
Handling Errors
17
JF 6-2
Handling Errors
18
I/O Exception
This code uses a try/catch block to handle an I/O exception.
try{
FileReader reader = new FileReader("test.txt");
}
catch(IOException e){
System.out.println("File not found");
}
JF 6-2
Handling Errors
19
JF 6-2
Handling Errors
20
Throwing Exceptions
So far you have seen exceptions handled by using a try/catch
block.
You can also handle exceptions by throwing them.
If you throw an exception, your interpreter will stop running
the program at that point, which indicates to the user that
they have reached the exception.
In code, an exception is thrown as follows:
throw new Exception("Array index" + i + " is out of bounds!");
JF 6-2
Handling Errors
21
Catching Exceptions
To catch an exception means to handle it.
You may throw an exception for certain cases, such as going
out of bounds of an array, and catch the exception to
continue the program the way you wrote it to handle the
exception.
A try/catch block enables you to do this.
JF 6-2
Handling Errors
22
Try/Catch Example
This is an example of handling an Index Out Of Bounds
exception with a try/catch block.
try{
}
catch(Exception e){
//This code will run only if the exception was thrown
if(i > 9)
i-=9;
else
i+=9;
}
//You may have additional code here that will run only if the exception was not thrown
JF 6-2
Handling Errors
23
JF 6-2
Handling Errors
24
Terminology
Key terms used in this lesson included:
Catch
Checked exceptions
Error
Exception
Logic error
JF 6-2
Handling Errors
25
Terminology
Key terms used in this lesson included:
Runtime error
Syntax error
Throw
Try/catch block
Unchecked exceptions
JF 6-2
Handling Errors
26
Summary
In this lesson, you should have learned how to:
Describe the different kinds of errors that can occur and how
they are handled in Java
Describe what exceptions are used for in Java
Determine what exceptions are thrown for any foundation
class
Write code to handle an exception thrown by the method of a
foundation class
JF 6-2
Handling Errors
27
Java Fundamentals
7-1
Classes, Objects, and Methods
Objectives
This lesson covers the following objectives:
Recognize the correct general form of a class
Create an object of a class
Create methods that compile with no errors
Return a value from a method
Use parameters in a method
Create a driver class and add instances of Object classes
JF 7-1
Classes, Objects, and Methods
Objectives
This lesson covers the following objectives:
Add a constructor to a class
Apply the new operator
Describe garbage collection and finalizers
Apply the this reference
Add a constructor to initialize a value
JF 7-1
Classes, Objects, and Methods
JF 7-1
Classes, Objects, and Methods
//constructor
public Vehicle(){
}
//mutator/setter method
public void setMake(String m){
make = m;
}
//mutator/setter method
public void setMilesPerGallon(int mpg){
milesPerGallon = mpg;
}
//accessor/getter method
public String getMake(){
return make;
}
//accessor/getter method
public int getMilesPerGallon(){
return milesPerGallon;
}
JF 7-1
Classes, Objects, and Methods
JF 7-1
Classes, Objects, and Methods
Instantiate an Instance
To instantiate an instance of a Vehicle called myCar, write:
public class VehicleTester{
public static void main(String[] args){
Vehicle myCar = new Vehicle();
}
}
JF 7-1
Classes, Objects, and Methods
Constructors
Constructors are methods that
allow the user to create instances of
(instantiate) a class.
Good programming practice
dictates that classes should have a
default constructor.
Constructors which contain
parameters typically initialize the
private variables of the class to
values passed in by the user.
Constructors do not have a return
type (void or other).
JF 7-1
Classes, Objects, and Methods
Default Constructor
Good programming practice dictates that classes should have
a default constructor.
A default constructor:
Takes no parameters.
Typically initializes all private variables to base values.
public Vehicle() {
make = "";
milesPerGallon = 0;
}
JF 7-1
Classes, Objects, and Methods
10
Parameters
JF 7-1
Classes, Objects, and Methods
11
JF 7-1
Classes, Objects, and Methods
12
Defining Methods
A method is a block of code which is referred to by name and
can be called at any point in a program simply by utilizing the
method's name. There are four main parts to defining your
own method:
JF 7-1
Classes, Objects, and Methods
13
Components of a Method
Method components include:
Return type:
This identifies what type of object, if any, will be returned when the method
is invoked (called).
If nothing will be returned, the return type is declared as void.
Method name:
Used to make a call to the method.
JF 7-1
Classes, Objects, and Methods
14
Components of a Method
Parameter(s):
The programmer may choose to include parameters depending on the
purpose and function of the method.
Parameters can be of any primitive or type of object, but the
parameter type used when calling the method must match the
parameter type specified in the method definition.
JF 7-1
Classes, Objects, and Methods
15
Return type
Name of method
Parameters
JF 7-1
Classes, Objects, and Methods
16
Class Methods
Every class will have a set of methods associated with it which
allow functionality for the class.
Accessor method
"getter"
Returns the value of a specific private variable.
Mutator method
"setter"
Changes or sets the value of a specific private variable.
Functional method
Returns or performs some sort of functionality for the class.
JF 7-1
Classes, Objects, and Methods
17
Accessor Methods
Accessor methods access and return the value of a specific
private variable of the class.
Non-void return type corresponds to the data type of the
variable you are accessing.
Include a return statement.
Usually have no parameters.
public String getMake(){
return make;
}
public int getMilesPerGallon(){
return milesPerGallon;
}
JF 7-1
Classes, Objects, and Methods
18
Mutator Methods
Mutator methods set or modify the value of a specified
private variable of the class.
Void return type.
Parameter with a type that corresponds to the type of the
variable being set.
public void setMake(String m){
make = m;
}
public void setMilesPerGallon(int mpg){
milesPerGallon = mpg;
}
JF 7-1
Classes, Objects, and Methods
19
Functional Methods
Functional methods perform a functionality for the class.
Void or non-void return type.
Parameters are optional and used depending on what is
needed for the method's function.
JF 7-1
Classes, Objects, and Methods
20
Functional Methods
Below is a functional method for the class Vehicle that
compares two vehicles and returns an int value for the
comparison.
//Compares the miles per gallon of each vehicle passed in, returns 0 if
they are the same, 1 if the first vehicle is larger than the second and -1
if the second vehicle is larger than the first*/
public int compareTo(Vehicle v1, Vehicle v2){
if(v1.getMilesPerGallon()= = v2.getMilesPerGallon())
return 0;
if(v1.getMilesPerGallon()> v2.getMilesPerGallon())
return 1;
return -1;
}
JF 7-1
Classes, Objects, and Methods
21
System.out.print("My "+v.getMake() +
" gets " + v.getMilesPerGallon() + " mpg.");
JF 7-1
Classes, Objects, and Methods
22
this Reference
Within an instance method or a constructor, this is a
reference to the current object.
The reference to the object whose method or constructor is
being called.
Refer to any member of the current object by using this.
Most commonly used when a field is shadowed by a method
or constructor parameter of the same name.
JF 7-1
Classes, Objects, and Methods
23
//constructor
public Point(int x, int y) {
this.x = x;
this.y = y;
}
JF 7-1
Classes, Objects, and Methods
24
JF 7-1
Classes, Objects, and Methods
25
suit = null
name= null
points = 0
JF 7-1
Classes, Objects, and Methods
26
JF 7-1
Classes, Objects, and Methods
27
Finalizers
A finalizer is code called by the garbage collector when it
determines no more references to the object exist.
All objects inherit a finalize() method from java.lang.Object.
This method takes no parameters and is written to perform
no action when called.
JF 7-1
Classes, Objects, and Methods
28
Finalizers
Overriding the finalize() method in classes allows you to
modify what happens before garbage collection, such as:
Notifying the user about the garbage collection that is about to occur.
Cleaning up non-Java resources, such as closing a file.
JF 7-1
Classes, Objects, and Methods
29
JF 7-1
Classes, Objects, and Methods
30
Terminology
Key terms used in this lesson included:
Accessor method
Class
Constructor
Finalizers
Garbage collection
Initialization
Instantiate
Method
JF 7-1
Classes, Objects, and Methods
31
Terminology
Key terms used in this lesson included:
Mutator method
new
Null
Object
Reference
this Reference
JF 7-1
Classes, Objects, and Methods
32
Summary
In this lesson, you should have learned how to:
Recognize the correct general form of a class
Create an object of a class
Create methods that compile with no errors
Return a value from a method
Use parameters in a method
Create a driver class and add instances of Object classes
JF 7-1
Classes, Objects, and Methods
33
Summary
In this lesson, you should have learned how to:
Add a constructor to a class
Apply the new operator
Describe garbage collection and finalizers
Apply the this reference
Add a constructor to initialize a value
JF 7-1
Classes, Objects, and Methods
34
Java Fundamentals
7-2
Parameters and Overloading Methods
Objectives
This lesson covers the following objectives:
Use access modifiers
Pass objects to methods
Return objects from methods
Use variable argument methods
Overload constructors
Overload methods
Write a class with specified arrays, constructors, and methods
JF 7-2
Parameters and Overloading Methods
Access Modifiers
Access modifiers specify accessibility to changing variables,
methods, and classes.
There are four access modifiers in Java:
Access Modifier
Description
public
protected
private
JF 7-2
Parameters and Overloading Methods
JF 7-2
Parameters and Overloading Methods
Declaring as public
The code below shows how to declare a variable, method, or
class as public.
Variable:
public int milesRan = 2;//public access
int timePassed = 17;//access not specified
Method:
public int addMiles(int a, int b)
{
return a+b;
}
Class:
public class Jogging{
//class code here
}
JF 7-2
Parameters and Overloading Methods
JF 7-2
Parameters and Overloading Methods
JF 7-2
Parameters and Overloading Methods
Type
public
private
Definition
When to Use
JF 7-2
Parameters and Overloading Methods
Objects as Parameters
A parameter is a variable in a method declaration that is
passed to the method.
public int method(int parameter1, int parameter2)
JF 7-2
Parameters and Overloading Methods
10
JF 7-2
Parameters and Overloading Methods
11
JF 7-2
Parameters and Overloading Methods
12
Returning Objects
Writing a method that returns an object is very similar to
writing a method that returns a primitive type.
For example, the employer from the previous example just
learned that methods can return an object.
To make it easier to find the employee to promote, he can
write a method that takes in two employees.
The method returns the one that has a better rating.
This is easier than going through each employee, retrieving
each of their ratings, and then comparing them.
JF 7-2
Parameters and Overloading Methods
13
JF 7-2
Parameters and Overloading Methods
14
JF 7-2
Parameters and Overloading Methods
15
JF 7-2
Parameters and Overloading Methods
16
JF 7-2
Parameters and Overloading Methods
17
JF 7-2
Parameters and Overloading Methods
18
Employee Example
To determine employee promotions, the employer was
coding a method that compared two employees and returned
the best one.
Now that the employer has the method to compare the
employees, he needs a way to compare all the employees at
once instead of only comparing two at a time.
This is where variable arguments would help.
JF 7-2
Parameters and Overloading Methods
19
JF 7-2
Parameters and Overloading Methods
20
JF 7-2
Parameters and Overloading Methods
21
JF 7-2
Parameters and Overloading Methods
22
Overloading Constructors
Constructors assign initial
values to instance variables of
a class.
Constructors inside a class are
declared like methods.
Overloading a constructor
means having more than one
constructor with the same
name but different types
and/or numbers of arguments.
JF 7-2
Parameters and Overloading Methods
23
JF 7-2
Parameters and Overloading Methods
24
JF 7-2
Parameters and Overloading Methods
25
public Dog(){
weight = 12;
loudness = 4;
barkNoise = "Woof";
}
public Dog(int w, int l){
weight = w;
loudness = l;
barkNoise = "ARF!";
public Dog(int w, int l, String bark){
weight = w;
loudness = l;
barkNoise = bark;
}
JF 7-2
Parameters and Overloading Methods
26
JF 7-2
Parameters and Overloading Methods
27
JF 7-2
Parameters and Overloading Methods
28
JF 7-2
Parameters and Overloading Methods
29
Overloading Methods
Like overloading constructors, overloading a method occurs
when the type and/or number of parameters differ. Below is
an example of a situation where a method would need to be
overloaded. Create the Dog class, then create an instance of
Dog in a Driver Class. Call (use) both bark() methods.
public class Dog{
private int weight;
private int loudness;
private String barkNoise;
public void bark(String b){
System.out.println(b);
JF 7-2
Parameters and Overloading Methods
30
Terminology
Key terms used in this lesson included:
Access modifier
Constructor
Default constructor
Overloading
Private access modifier
Public access modifier
Variable argument method
JF 7-2
Parameters and Overloading Methods
31
Summary
In this lesson, you should have learned how to:
Use access modifiers
Pass objects to methods
Return objects from methods
Use variable argument methods
Overload constructors
Overload methods
Write a class with specified arrays, constructors, and methods
JF 7-2
Parameters and Overloading Methods
32
Java Fundamentals
7-3
The Static Modifier and Nested Classes
Objectives
This lesson covers the following objectives:
Create static variables
Use static variables
Create static methods
Use static methods
Create static classes
Use static classes
JF 7-3
The Static Modifier and Nested Classes
Static Modifier
Using instance variables, each instance of a class created with
the keyword new creates a copy of all instance variables in
that class.
For example, in the Employee class below, a unique copy of
lastname and firstname is created for each new Employee
object that is created in a Driver Class.
public class Employee{
private String lastname;
private String firstname;
...more code
}
//create two Employees in a main method:
Employee e1 = new Employee("Smith", "Mary");
Employee e2 = new Employee("Jones", "Sally");
JF 7-3
The Static Modifier and Nested Classes
Static Keyword
Static is a keyword in Java that modifies the association of an
item to a class.
Contents of a class that are identified as static are shared
across all instances of the class.
This means all instances of the class share one copy of the
static items, and each have their own unique copies of
instance items, or non-static items.
JF 7-3
The Static Modifier and Nested Classes
Static Example
Consider initializing a static String with the value "Oracle"
called myCompany that represents the employer's company.
Each instance of Employee would still have their unique
instance variables, but would share the static variable.
e2
e1
Instance Variable
Static Variable
Instance Variable
Mary Smith
Oracle
Sally Jones
JF 7-3
The Static Modifier and Nested Classes
Static Variables
Static variables
Are also known as class variables.
Are declared with the static keyword.
Have only one copy in memory, as opposed to instance
variables, which hold one copy per instance.
Are shared by object instances.
Hold the same value for all class instances.
JF 7-3
The Static Modifier and Nested Classes
Static Variables
Public access for static variables:
If public, they can be modified directly by other classes.
Consider making the variable a constant by using the keyword final to
prevent modifications.
Example:
public static final int MODEL_NUM = 883;
JF 7-3
The Static Modifier and Nested Classes
JF 7-3
The Static Modifier and Nested Classes
JF 7-3
The Static Modifier and Nested Classes
10
11
JF 7-3
The Static Modifier and Nested Classes
12
JF 7-3
The Static Modifier and Nested Classes
13
JF 7-3
The Static Modifier and Nested Classes
14
15
JF 7-3
The Static Modifier and Nested Classes
16
JF 7-3
The Static Modifier and Nested Classes
17
JF 7-3
The Static Modifier and Nested Classes
18
getTankOfResidence() are
instance, non-static, methods
because they access non-static
variables. Static methods cannot
access non-static items.
19
20
JF 7-3
The Static Modifier and Nested Classes
21
JF 7-3
The Static Modifier and Nested Classes
22
JF 7-3
The Static Modifier and Nested Classes
23
JF 7-3
The Static Modifier and Nested Classes
24
Terminology
Key terms used in this lesson included:
Class method
Class variable
Inner class
Nested class
Static modifier
Static method
Static nested class
Static variable
JF 7-3
The Static Modifier and Nested Classes
25
Summary
In this lesson, you should have learned how to:
Create static variables
Use static variables
Create static methods
Use static methods
Create static classes
Use static classes
JF 7-3
The Static Modifier and Nested Classes
26
Java Fundamentals
7-4
Inheritance
Objectives
This lesson covers the following objectives:
Demonstrate and explain UML (Unified Modeling Language)
class diagrams
Use the extends keyword to inherit a class
Compare and contrast superclasses and subclasses
Describe how inheritance affects member access
Use super to call a superclass constructor
Use super to access superclass members
Create a multilevel class hierarchy
JF 7-4
Inheritance
Overview
This lesson covers the following topics:
Recognize when constructors are called in a class hierarchy
Demonstrate understanding of inheritance through the use
of applets
Recognize correct parameter changes in an existing applet
JF 7-4
Inheritance
What is Inheritance?
Inheritance is a simple but powerful tool of
object oriented languages that allows classes
to inherit methods and fields from other
classes.
Inherit means to receive or obtain something
from your predecessor or parent.
In Java, the concept of inheritance is similar
to genetics.
Genes and genetic traits are passed down from
parent to child.
Children often look and act like their parents as a
result.
JF 7-4
Inheritance
JF 7-4
Inheritance
Subclass
JF 7-4
Inheritance
Superclass
Specific
Subclass
JF 7-4
Inheritance
Inheritance Example
Create a Shape class with a variable, color, and one method
which returns the color. Create a Rectangle class which
inherits the variable and method from Shape, and can have
its own methods and variables.
Shape (superclass)
public String color
public String getColor()
Rectangle (subclass)
public String color
public String getColor()
//Rectangle-only data
public int length
public int width
public int getLength()
public int getWidth()
JF 7-4
Inheritance
JF 7-4
Inheritance
General
Animal
Specific
Crab
10
JF 7-4
Inheritance
11
JF 7-4
Inheritance
12
extends Keyword
In Java, you have the choice of which classes you want to
inherit from by using the keyword extends.
The keyword extends allows you to designate the superclass
that has methods you want to inherit, or whose methods and
data you want to extend.
For example, to inherit methods from the Shape class, use
extends when the Rectangle class is created.
public class Rectangle extends Shape
{
//code
}
JF 7-4
Inheritance
13
JF 7-4
Inheritance
14
JF 7-4
Inheritance
15
JF 7-4
Inheritance
16
JF 7-4
Inheritance
17
Specific
Superclass
Subclass
JF 7-4
Inheritance
18
Object Example 1
Object contains methods that can be used on every class
(such as toString(), or equals()).
For example, after you create a class and construct an
instance of it, can you call the method toString() on your
object?
A_Class class = new A_Class();
class.toString();
Yes. Even though you did not write the method toString(), it is
still legal for you to call this method because it was inherited
from Object.
JF 7-4
Inheritance
19
Object Example 2
Is class.toString() legal if A_Class explicitly extends
Another_Class, a superclass?
Yes. This is also legal since the superclass of A_Class extends
Object.
A_Class class = new A_Class();
class.toString();
JF 7-4
Inheritance
20
JF 7-4
Inheritance
21
Inheritance Hierarchies
In many situations, it's common to classify concepts as
hierarchies.
A hierarchy is a way of categorizing the relationship among
ideas, concepts or things with the most general or allencompassing component at the top and the more specific,
or the component with the narrowest scope, at the bottom.
Hierarchies are a useful concept when it comes to inheritance
and can be used to model and organize the relationship
among superclasses and subclasses.
JF 7-4
Inheritance
22
Tree Diagrams
Hierarchies can be organized into tree diagrams.
Computer Scientists will often refer to trees having leaves and
branches, or will refer to the "leaves" as nodes.
For example, shapes can be categorized by different
properties, such as their number of sides.
Branch
Triangle
Shape
Rectangle
Leaf/Node
Circle
Square
JF 7-4
Inheritance
23
Tree Diagrams
Notice that Circle, Triangle, and Rectangle all have a different
number of sides, so they are different branches in the tree.
Only nodes with the same properties will occupy the same
branch.
Shape
Triangle
Rectangle
Circle
Square
JF 7-4
Inheritance
24
Triangle
Rectangle
Square
JF 7-4
Inheritance
Circle
Type
25
26
JF 7-4
Inheritance
27
JF 7-4
Inheritance
28
Shape
Attributes
Color
Methods
getColor()
JF 7-4
Inheritance
29
JF 7-4
Inheritance
30
Symbol
Inheritance
Rectangle
public int length
public int width
public int getLength()
public int getWidth()
JF 7-4
Inheritance
Shape
String color
getColor()
31
Encapsulation
Encapsulation is a fundamental concept in object oriented
programming.
Encapsulation means to enclose something into a capsule or
container, such as putting a letter in an envelope. In object-oriented
programming, encapsulation encloses, or wraps, the internal workings
of a Java instance/object
JF 7-4
Inheritance
32
33
JF 7-4
Inheritance
34
Access Modifiers
Programmers can customize the visibility of their data and
methods with several levels of access modifiers.
Access Modifier
Accessed by:
public
private
protected
"default"
JF 7-4
Inheritance
35
JF 7-4
Inheritance
36
JF 7-4
Inheritance
37
Member Access
Use the keyword private to hide data that only the class
should be able to change. (This is the recommended access
modifier.) If access to the data is needed, then a getter
method should be written to achieve this.
public class Shape {
//the color of the Shape
private String color;
JF 7-4
Inheritance
38
Member Access
If the private variables need to be (or are allowed to be)
changed, then a setter method should be written.
public class Shape {
//the color of the Shape
private String color;
JF 7-4
Inheritance
39
JF 7-4
Inheritance
40
Not recommended
JF 7-4
Inheritance
41
Accessed by:
public
All classes.
private
protected
"default"
JF 7-4
Inheritance
42
JF 7-4
Inheritance
43
Inheriting Constructors
Although a subclass inherits all of the methods and fields
from a parent class, it does not inherit constructors.
You can:
Write your own constructor or constructors.
Use the default constructor.
If you do not declare a constructor, a default no-argument constructor is
provided for you.
If you declare your own constructor, the default constructor is no longer
provided.
JF 7-4
Inheritance
44
JF 7-4
Inheritance
45
JF 7-4
Inheritance
46
//Constructor
public Rectangle(String color, int length, int width)
{
This calls the constructor for
super(color);
Shape, which initializes the
this.length = length;
variable color.
this.width = width;
}
JF 7-4
Inheritance
47
JF 7-4
Inheritance
48
JF 7-4
Inheritance
49
JF 7-4
Inheritance
50
JF 7-4
Inheritance
51
Size Parameter
Although Squares are a type of Rectangle, they have a unique
property such that length = width.
Accommodate this by only requiring one size parameter that
sets both the width and length values.
public class Square extends Rectangle {
JF 7-4
Inheritance
52
JF 7-4
Inheritance
53
Customize Methods
Because a Square has the same values for height and width,
we want to customize the methods setWidth(int width) and
setHeight(int height) so that both are updated when the
method is called.
Use the keyword super to call the superclass's methods
setLength() and setWidth() and set them both to the
parameter value passed to the method.
public int setWidth(int width){
super.setLength(width);
super.setWidth(width);
}
JF 7-4
Inheritance
54
Square Subclass
The final product will look like the following:
public class Square extends Rectangle {
JF 7-4
Inheritance
55
JF 7-4
Inheritance
56
JF 7-4
Inheritance
57
Creating Applets
To create an applet, you can borrow all of the core methods
in the Applet class and customize these methods to suit the
particular needs of your applet.
JF 7-4
Inheritance
58
Creating Applets
For example, to make an applet that draws Shapes, start by
setting up the inheritance with extends:
public class DrawShapes extends Applet
...
}
JF 7-4
Inheritance
59
Applet Example
import
import
import
import
public
java.applet.Applet;
java.awt.Graphics;
java.awt.Graphis2D;
java.awt.Rectangle;
class RectangleApplet extends Applet{
JF 7-4
Inheritance
60
Terminology
Key terms used in this lesson included:
Access modifiers
Child class
default
Encapsulation
extends
Hierarchy
Inheritance
"is-a" relationship
JF 7-4
Inheritance
61
Terminology
Key terms used in this lesson included:
Parent class
private
protected
public
Subclass
super
Superclass
Unified Modeling Language (UML)
JF 7-4
Inheritance
62
Summary
In this lesson, you should have learned how to:
Demonstrate and explain UML (Unified Modeling Language)
class diagrams
Use the extends keyword to inherit a class
Compare and contrast superclasses and subclasses
Describe how inheritance affects member access
Use super to call a superclass constructor
Use super to access superclass members
JF 7-4
Inheritance
63
Summary
In this lesson, you should have learned how to:
Create a multilevel class hierarchy
Recognize when constructors are called in a class hierarchy
Demonstrate understanding of inheritance through the use
of applets
Recognize correct parameter changes in an existing applet
JF 7-4
Inheritance
64
Java Fundamentals
7-5
Polymorphism
Objectives
This lesson covers the following objectives:
Apply superclass references to subclass objects
Write code to override methods
Use dynamic method dispatch to support polymorphism
Create abstract methods and classes
Recognize a correct method override
JF 7-5
Polymorphism
Overview
This lesson covers the following topics:
Use the final modifier
Explain the purpose and importance of the Object class
Write code for an applet that displays two triangles of
different colors
Describe object references
JF 7-5
Polymorphism
Review of Inheritance
When one class inherits from another, the subclass "is-a"
type of the superclass.
Objects of a subclass can be referenced using a superclass
reference, or type.
JF 7-5
Polymorphism
Learn More
Visit Oracle's tutorial pages to learn more:
Inheritance:
http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html
Polymorphism:
http://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html
JF 7-5
Polymorphism
Inheritance Example
If classes are created for a Bicycle class and a RoadBike class
that extends Bicycle, a reference of type Bicycle can reference
a RoadBike object.
Because RoadBike "is-a" type of Bicycle, it is perfectly legal to
store a RoadBike object as a Bicycle reference.
The type of a variable (or reference) does not determine the
actual type of the object that it refers to.
JF 7-5
Polymorphism
Inheritance Example
Therefore, a Bicycle reference, or variable, may or may not
contain an object of the superclass type Bicycle since it can
contain any subclass of Bicycle.
Bicycle bike = new RoadBike();
JF 7-5
Polymorphism
Polymorphism
When a variable or reference may refer to different types of
objects is called polymorphism.
Polymorphism is a term that means "many forms".
In the case of programming, polymorphism allows variables
to refer to many different types of objects, meaning they can
have multiple forms.
For example, because RoadBike "is-a" Bicycle, there are two
possible references that define the type of object it is (Bicycle
or RoadBike).
JF 7-5
Polymorphism
JF 7-5
Polymorphism
10
JF 7-5
Polymorphism
11
Superclass Variables
If you "open up" a superclass variable, or invoke one of its
methods, you will find that you actually have a subclass
object stored inside.
For example, with nesting dolls, you cannot see the smaller
doll until you open the larger doll. Its type may be ambiguous.
When Java code is compiled, Java does not check to see what
type (supertype or subtype) of object is inside a variable.
When Java code is executed, Java will "open up" to see what
type of object is inside the reference, and call methods that
are of that type.
JF 7-5
Polymorphism
12
13
JF 7-5
Polymorphism
14
JF 7-5
Polymorphism
15
Object References
The Object class is the highest superclass in Java, since it does
not extend another class.
As a result, any class can be stored in an Object reference.
Object[] objects = new Bicycle[size];
JF 7-5
Polymorphism
16
17
18
Overriding Methods
Overriding methods is a way of redefining methods with the
same return type and parameters by adding, or overriding
the existing logic, in a subclass method.
Overriding is different than overloading a method.
Overloading a method means the programmer keeps the
same name (i.e. toString()), but changes the input parameters
(method signature).
Overriding essentially hides the parent's method with the
same signature, and it will not be invoked on a subclass
object unless the subclass uses the keyword super.
JF 7-5
Polymorphism
19
Overriding Methods
Overriding does not change the parameters.
It only changes the logic inside the method defined in the
superclass.
JF 7-5
Polymorphism
20
JF 7-5
Polymorphism
21
Overriding toString()
We can override toString() to return a String that provides
information about the object instead of the location of the
object in memory. First, start with the prototype:
public String toString()
JF 7-5
Polymorphism
22
Overriding toString()
The result for our overridden toString() method:
public String toString(){
return "Model: " + modelNum +
" Color: " + color +
" Frame Type: " + frameType +
" Price: " + price;
JF 7-5
Polymorphism
23
JF 7-5
Polymorphism
24
JF 7-5
Polymorphism
25
JF 7-5
Polymorphism
26
JF 7-5
Polymorphism
27
JF 7-5
Polymorphism
28
Abstract Classes
Is it really necessary to define a Bicycle class if we are only
going to create objects of its subclasses: roadBikes and
mountainBikes?
Abstract classes are one alternative that addresses this
concern.
An abstract class is one that cannot be instantiated:
This means that you cannot create objects of this type.
It is possible to create variables, or references of this type.
JF 7-5
Polymorphism
29
Abstract Classes
If we declare the Bicycle class to be abstract, we can still use
the syntax below, but we cannot actually create a Bicycle
object.
This means all references of type Bicycle will reference
subclass objects MountainBike or RoadBike.
Bicycle bike = new RoadBike();
JF 7-5
Polymorphism
30
Abstract Classes
Abstract classes can contain fully-implemented methods that
they "pass on" to any class that extends them.
Make a class abstract by using the keyword abstract.
public abstract class Bicycle
JF 7-5
Polymorphism
31
Abstract Classes
Abstract classes can also declare at least one abstract method
(method that does not contain any implementation.
This means the subclasses must use the method prototype
(outline) and must implement these methods.
Abstract methods are declared with the abstract keyword.
abstract public void setPrice();
Declare as abstract
public. Do not use {}.
JF 7-5
Polymorphism
32
Abstract Methods
Abstract methods:
Cannot have a method body.
Must be declared in an abstract class.
Must be overridden in a subclass.
JF 7-5
Polymorphism
33
34
JF 7-5
Polymorphism
35
JF 7-5
Polymorphism
36
JF 7-5
Polymorphism
37
Using Final
Although it is nice to have the option, in some cases, you may
not want some methods to be overridden or to have your
class extended.
Java provides a tool to prevent programmers from overriding
methods or creating subclasses: the keyword final.
JF 7-5
Polymorphism
38
Using Final
A good example is the String class.
It is declared:
public final class String {}
JF 7-5
Polymorphism
39
Using Final
The final modifier can be applied to variables.
Final variables may not change their values after they are
initialized.
JF 7-5
Polymorphism
40
Using Final
Final variables can be:
Class fields
Final fields with compile-time constant expressions are constant variables.
Static can be combined with final to create an always-available, neverchanging variable.
Method parameters
Local variables
JF 7-5
Polymorphism
41
Using Final
Final references must always reference the same object.
The object to which the variable is referencing cannot be
changed.
The contents of that object may be modified.
Visit Oracle's Java tutorial for more information on using final:
http://docs.oracle.com/javase/tutorial/java/IandI/final.html
JF 7-5
Polymorphism
42
JF 7-5
Polymorphism
43
JF 7-5
Polymorphism
44
JF 7-5
Polymorphism
45
Terminology
Key terms used in this lesson included:
abstract
Dynamic Method Dispatch
final
Immutable
Overloading methods
Overriding methods
Polymorphism
JF 7-5
Polymorphism
46
Summary
In this lesson, you should have learned how to:
Apply superclass references to subclass objects
Write code to override methods
Use dynamic method dispatch to support polymorphism
Create abstract methods and classes
Recognize a correct method override
JF 7-5
Polymorphism
47
Summary
In this lesson, you should have learned how to:
Use the final modifier
Explain the purpose and importance of the Object class
Write code for an applet that displays two triangles of
different colors
Describe object references
JF 7-5
Polymorphism
48