What We Will Cover
Illuminations
Questions from last class or the Reading?
Midterm Questions
Homework Questions?
^ top
7.1: Reviewing Newton's Lab
Learner Outcomes
At the end of the lesson the student will be able to:
Describe vectors
Work with an abstract class
Discuss mixed mode arithmetic
Write overloaded constructors and methods
Prevent shadowing of variables
Use this() within a constructor
^ top
7.1.1: Interacting Objects and Abstraction
Concept Review
Abstract class : a superclass that cannot be instantiated
Constant : a variable that you cannot change
Collection : a type of object that can hold many other objects
Generic type : a type that needs a second type name as a parameter
List : a type of collection where objects are stored in an order
null: a special word for "no object"
Overloading : same method name for two different methods or constructors
this(): used to call one constructor from another
Reviewing the Newton's Lab Scenario
Abstract Classes
The scenario uses two helper classes: SmoothMover and Vector
SmoothMover is the superclass of Body
If we right-click on SmoothMover, we notice that we cannot create an object
Examining SmoothMover, we see that it has a new keyword in the header: abstract
We declare classes abstract when we do NOT want to create objects from them
Abstract classes serve only as superclasses for other classes
Check Yourself
When we simplify a set of real objects, like astronomical objects, to basic shared characteristics, like a Body class, we are using a process known as ________ .
abstraction
an abstract class
summarization
deep thought
True or false: we can use a parameter in a constructor to customize how an object operates.
True or false : An abstract class can be created by right-clicking on the class in Greenfoot.
True or false : All abstractions are composed in abstract classes.
^ top
7.1.2: Vectors
Objects that move (for example planets) have a velocity
Velocity is both a speed (such as 100 MPH) and a direction (such as up)
Because of these two aspects, velocity is often represented as a vector
A vector is a geometric object with both direction and length (magnitude)
Thus we often use vectors to represent velocity
The above representation is known as polar coordinates
Another way to represent a vector is as a pair of distances (dx , dy )
The d in (dx , dy ) stands for delta , a Greek letter used in science and engineering to mean a change
Here is the same vector using (dx , dy ):
This second image is called the Cartesian representation
The book used a separate Vector class to work with vectors
The Vector class is used by the SmoothMover class to control movement
Check Yourself
A geometric object with both direction and length is called a(n) ________ .
Specifying a vector using direction and length is known as the ________ representation.
Specifying a vector as a pair of distances (dx , dy ) is known as the ________ representation.
^ top
7.1.3: Smooth Moving and Type double
The purpose of SmoothMover is to position and smoothly move objects on the screen
It works by using floating-point (decimal) numbers rather than integers
For example, SmoothMover can have the x-coordinate 21.3
The important thing to notice is the decimal point
If we move an actor along the x -coordinate in increments of 0.7 we have:
21.3, 22.0, 22.7, 23.4, 24.1, 24.8, ...
Since a screen only allows integer numbers, we have to convert the numbers to integers:
21, 22, 23, 23, 24, 25, ...
Even though the numbers are rounded for display, the effect is smoother movement
Floating-Point Data Types
Mixed-Mode Arithmetic
Remember from lesson 4.3.3 that different data types are stored in different forms
An int is stored in 4 bytes in a binary format
A double is stored in 8 bytes using a complex format defined by IEEE 754
The computer needs both numbers in the same form before it can do arithmetic
If one operand is different than the other, the compiler converts it to the wider of the two types
For example:
2 + 2.3
The first number (2) is an int
The second number (2.3) is a double
Java will automatically convert the int to a double (2.0)
Then the computer knows how to do the arithmetic to produce a result of 4.3
Remember that the result of arithmetic with an int and a double is always a double
Check Yourself
^ top
7.1.4: Overloading Constructors and Methods
In the SmoothMover class, notice that there are two different constructors:
public SmoothMover()
public SmoothMover(Vector movement)
What is the same between these constructors? What is different?
These two constructors allow us to create a new SmoothMover object in two different ways
For example:
SmoothMover s1 = new SmoothMover();
SmoothMover s2 = new SmoothMover(new Vector(90, 2.2));
When there is more than one constructor in a class, the constructor is said to be overloaded
Overloading : having the same method name for two different constructors or methods.
When constructors or methods are overloaded, they must have different parameter lists
The first constructor has no parameters and is sometimes called a default constructor
A default constructor sets instance variables to default values
Method Overloading
Check Yourself
When two constructors or methods have the same name, this is known as ________ .
overridding
overloading
overwhelming
not possible
When different constructors or methods have the same name, they must have different ________ .
Of the following methods within a single class, ________ and ________ cannot exist at the same time.
public int foo(int a)
public int foo(int a, int b)
public int foo(double a)
public int foo(double a, double b)
public int foo(int b)
^ top
7.1.5: More About this
Remember from lesson 5.2.5 that the keyword this means this current object
Sometimes the keyword this is used to avoid a problem known as shadowing
Shadowing
Another Use for this
Check Yourself
The problem with the following code is ________ .
private int bar;
public void foo(int bar)
{
bar = bar;
}
What are two ways to correct the above problem?
In the following code, this() is used to ________ .
public Baz()
{
this(42);
}
^ top
Exercise 7.1
In this exercise, we explore the new concepts in our scenario. As you do, you will need to record all the stated questions and their answers in a text file using a text editor .
Specifications
Download the Newtons-Lab-2 scenario file and save it to a convenient location like the Desktop.
Scenario file: Newtons-Lab-2.zip .
Start Greenfoot and open the scenario.
Greenfoot unzips the file for us.
Run the scenario and remember how it operates by trying out the three initializing methods:
sunAndPlanet()
sunAndTwoPlanets()
sunPlanetMoon()
Locate the SmoothMover class and try to create a new SmoothMover object.
Q1: Were you able to construct an object?
Open the editor for the SmoothMover class and remove the word abstract from the class signature:
public abstract class SmoothMover extends Actor
Try to compile the modified SmoothMover class.
Q2: Were you able to construct an object after removing the abstract keyword?
Q3: Why would you declare a class abstract?
Restore the SmoothMover class to its original condition.
Compile the class and verify there are no errors. Resolve any errors you find, getting help from a classmate or the instructor as needed.
Examine the code for the SmoothMover class and find all the overloaded constructors and methods.
Q4: Which constructors and methods were overloaded (list their names)?
For more information see lesson: 7.1.4: Overloading Constructors and Methods .
In the SmoothMover class, find the following code in the first constructor:
this.movement = movement;
Change the code by removing the "this." so it looks like:
movement = movement;
Compile and run the scenario to see how it changed.
Q5: What change did you see?
Q6: Why did this change occur?
For more information see lesson: 7.1.5: More About this .
Restore the SmoothMover class to its original condition.
Compile the class and verify there are no errors. Resolve any errors you find, getting help from a classmate or the instructor as needed.
Using a text editor , create a text file named questions.txt and copy all the highlighted questions into the file. Next, record answers to all the questions in the file under the question.
Review your answers with another student in the class and correct any mistakes.
Add a comment to the top of the file that contains the name of the person with whom you reviewed the questions, like:
Reviewed with Jane Programmer
Save the questions.txt file so you can submit it to Blackboard as part of assignment 6.
As time permits, be prepared to answer the Check Yourself questions in the section: 7.1.6: Review .
^ top
7.1.6: Review
Answer these questions to check your understanding. You can find more information by following the links after the question.
Reducing a concept or idea to the most simple or basic shared characteristics is known as ________________. (7.1.1 )
True or false: All abstractions are composed in abstract classes. (7.1.1 )
To make a class from which you cannot instantiate an object use the keyword _________. (7.1.1 )
A geometric object with both direction and length is called a(n) _________. (7.1.2 )
Specifying a vector using direction and length is known as __________ representation. (7.1.2 )
Specifying a vector as a pair of distances (dx, dy) is known as __________ representation. (7.1.2 )
Which of the following is a valid declaration of a floating-point variable: (7.1.3 )
double scoop;
float boat;
int double;
totally double;
True or false: Of the two floating point types, the type you should normally use is double. (7.1.3 )
When adding an int and a double together, the resulting number is of type: (7.1.3 )
double
int
float
that depends on the number
When different constructors or methods have the same name they are said to be __________________. (7.1.4 )
Within a single class, which of the following methods can exist at the same time? (7.1.4 )
public int foo(int a)
public int foo(int a, int b)
public int foo(double a)
public int foo(double a, double b)
public int foo(int b)
Which is an example of overloading the method that follows? (7.1.4 )
public int calcValue(double number) {...}
public double calcValue(double number) {...}
int calcValue(double num) {...}
int calcValue(double number, int value) {...}
All of these
True or false: Shadowing is when a local variable or parameter has the same name as a member variable of a class. (7.1.5 )
What are two ways to avoid shadowing? (7.1.5 )
True or false: the following code calls another constructor in the same class: (7.1.5 )
public SmoothMover()
{
this(new Vector());
}
^ top
7.2: Applying Forces
Learner Outcomes
At the end of the lesson the student will be able to:
Write psuedocode to describe algorithms.
Write method stubs.
Write code to work with lists in Java.
Write enhanced for loops to process items in a list.
^ top
7.2.1: How a Body Moves
The move() method of SmoothMover updates and sets location of the actor
public void move()
{
exactX = exactX + movement.getX();
exactY = exactY + movement.getY();
super.setLocation((int) exactX, (int) exactY);
}
The act() method in Body calls the move() method
public void act()
{
applyForces();
move();
}
However, before the body moves we must apply the gravitational forces of all the other bodies in space
Algorithms and Psuedocode
Psuedocode Description of an Algorithm to Apply Gravity
Apply forces from other bodies:
get all other bodies in space;
for each of those bodies: {
apply gravity from that body to our own;
}
Check Yourself
A sequence of precise instructions to accomplish a task is called a(n) ________ .
The advantage of using psuedocode, instead of Java code, to describe an algorithm is we can omit the ________ details.
The line of the above pusedocode that describes a loop is ________ .
Use psuedocode to describe the algorithm for the move() method.
public void move()
{
exactX = exactX + movement.getX();
exactY = exactY + movement.getY();
super.setLocation((int) exactX, (int) exactY);
}
One possible answer
^ top
7.2.2: Implementing the applyForces Algorithm
Finding All the Bodies
Check Yourself
A method ________ is just enough code to allow the method to compile.
True or false : we add method stubs to our code as a placeholder until we write the method body.
The keyword null means no ________ .
Rewrite the following code in one statement rather than two:
World w = getWorld();
List<Actor> bodies = w.getObjects(Body.class);
answer
^ top
7.2.3: Working with Lists
When we work with collections of items, a natural approach is to use a list
Java has several classes for working with lists of data
List Types
When working with the Java library classes, look first at the Java API
Since getObjects() returns a List, look at the API for List
When we examine the API, we see that List is an interface and not a class
Interface List<E>
The List interface is a way for Java to specify a common set of methods for many different list classes
Which underlying list class the getObjects() method returns is not important
We just use the methods of the List interface as a common abstraction of the list classes
The following are some commonly used methods of List
Some Commonly Used Methods of List
Method
Description
add(item)
Adds the specified item to the end of the list.
add(index, item)
Adds the specified item at the specified index of the list.
get(index)
Retrieves the item at the specified index in the list.
remove(index)
Removes the item at the specified index in the list.
set(int index, item)
Replaces the item at the specified index in the list.
size()
Returns the number of items in the list.
Generic Types
Check Yourself
To add an item to a List, use the method ________ .
To remove an item to a List, use the method ________ .
To find out how many items a List contains, use the method ________ .
Write an assignment statement that declares a variable names and calls the following method, saving the returned value in the variable.
List<String> getNames() { /* ... */ }
answer
^ top
7.2.4: Applying the Forces
Method applyForces()
private void applyForces()
{
List<Body> bodies =
getWorld().getObjects(Body.class);
for (Body body : bodies)
{
if (body != this)
{
applyGravity (body);
}
}
}
Enhanced for Loop
Rewriting applyForces() Using a Standard for Loop
private void applyForces()
{
List<Body> bodies =
getWorld().getObjects(Body.class);
for (int i = 0; i < bodies.size(); i++)
{
Body body = bodies.get(i);
if (body != this)
{
applyGravity (body);
}
}
}
Check Yourself
In the applyForces() method, this refers to the ________ object.
True or false : The method applyForces() applies gravity from every object to the current object
Rewrite the following loop using an enhanced for loop:
int[] scores = {90, 95, 87, 89, 98};
for (int i = 0; i < scores.length; i++)
{
System.out.println(scores[i]);
}
Example answer
Which loop requires less code to write: standard or enhanced for loop?
^ top
7.2.5: Calculating Gravity
About Gravity
Gravity is a force of attraction between objects with mass
Newton's famous formula for gravity is shown in the following image from Wikipedia :
Where:
F: the force between the masses
G: the gravitational constant
m1 : mass of the first body
m2 : mass of the second body
r: distance between the masses
The complete applyGravity() method follows
Method applyGravity()
private void applyGravity(Body other)
{
double dx = other.getExactX() - this.getExactX();
double dy = other.getExactY() - this.getExactY();
Vector force = new Vector (dx, dy);
double distance = Math.sqrt(dx * dx + dy * dy);
double strength = GRAVITY * this.mass * other.mass
/ (distance * distance);
double acceleration = strength / this.mass;
force.setLength (acceleration);
addForce(force);
}
Notes on the Code
Distance in Relation to dx and dy
Check Yourself
________ is a force of attraction between objects with mass.
True or false : the numbers in applyGravity() need to be type double so they are precise.
The Math.sqrt() method has ________ parameter(s).
^ top
Exercise 7.2
In this exercise, we experiment with how changes in GRAVITY, mass and initial movement of the bodies affect the stability of the system.
Specifications
Start Greenfoot and open the Newton's Lab 2 scenario from the last exercise .
Run the scenario and remember how it operates by trying out the three initializing methods:
sunAndPlanet()
sunAndTwoPlanets()
sunPlanetMoon()
Change the gravity constant at the top of the Body class and see what happens.
private static final double GRAVITY = 5.8;
Try changing GRAVITY by 1/2, doubling it, changing it by 1 and by 0.1.
Choose your best value for GRAVITY. Then recompile and run the scenario to verify it works well.
If you have problems, ask a classmate or the instructor for help as needed.
Open the Space class and experiment with changes to the mass or initial movement of the bodies.
addObject(new Body (50, 0.8, new Vector(90, 3.25), ...);
// | | |
// mass direction movement
When experimenting you should change only one variable at a time.
Note that you may find it challenging to find a stable system. If so, you may want to read the Wikipedia article: Stability of the Solar System .
Save a copy of your scenario as we will be adding to it in the next exercise.
Only submit the final scenario with all the lesson exercises completed, not the intermediate scenarios.
As time permits, read the following sections and be prepared to answer the Check Yourself questions in the section: 7.2.6: Review .
^ top
7.2.6: Review
Answer these questions to check your understanding. You can find more information by following the links after the question.
What is an algorithm? (7.2.1 )
Why do people use psuedocode to describe an algorithm? (7.2.1 )
Use psuedocode to describe the algorithm for the following method:
public void move()
{
exactX = exactX + movement.getX();
exactY = exactY + movement.getY();
super.setLocation((int) exactX, (int) exactY);
}
Write a method stub for an algorithm that gets two numbers, adds them together and returns their sum. (7.2.2 )
What is the special word that stands for, "no object"? (7.2.2 )
What line or lines of code will get all the Body objects from within the Body class? (7.2.2 )
What methods of the List interface add items to a list? (7.2.3 )
What method of the List interface removes items from a list? (7.2.3 )
What methods of the List interface finds out how many items are in a list? (7.2.3 )
Write a statement that calls the following method and saves the returned value in the variable names: (7.2.3 )
List<String> getNames() { /* ... */ }
What does this refer to in the following method? (7.2.4 )
private void applyForces()
{
List<Body> bodies =
getWorld().getObjects(Body.class);
for (Body body : bodies)
{
if (body != this)
{
applyGravity (body);
}
}
}
Rewrite the following loop using an enhanced for loop: (7.2.4 )
int[] scores = {90, 95, 87, 89, 98};
for (int i = 0; i < scores.length; i++)
{
System.out.println(scores[i]);
}
Which loop requires less code to write: standard or enhanced for loop? (7.2.4 )
____________ is a force of attraction between objects with mass. (7.2.5 )
Write a statement that computes the square root of 42. (7.2.5 )
^ top
7.3: Gravity and Music
Learner Outcomes
At the end of the lesson the student will be able to:
Create a musical animation.
Write code to detect collisions between objects.
Write code to arrange objects in space.
^ top
7.3.1: Playing with Gravity
The Scenario
We have a set of obstacles that play musical notes when struck
Several planetary bodies, represented by the circles, move around the screen
The movement of the bodies is affected by their gravitational attraction
When one of the bodies strikes an obstacle, the obstacle plays a note
Do you recognize the musical sounds?
Changes Made
New Obstacles class added that plays a note when struck
Body class modified so it bounces at the edge of the screen
Space class changed to create a fixed row of obstacles
We will examine the changes in more detail in the following sections
Check Yourself
An obstacle plays a(n) ________ when struck by a body.
True or false : the scenario bodies are affected by gravity.
True or false : the planetary/obstacle system is stable.
^ top
7.3.2: Adding Obstacles
The purpose of the Obstacle class is to play a note when struck
As such, the obstacles are like the bars on a Xylophone or Glockenspiel
Looking at the code, each obstacle is assigned a sound in its constructor
The act() method checks if the obstacle was hit
If the obstacle was struck, it plays a sound
Collision Detection
Check Yourself
An obstacle plays a sound when ________ by a body.
A sound is assigned in the ________ of the Obstacle class.
When one object intersects another it is known as a(n) ________ .
The getOneIntersectingObject() method returns ________ when no object intersects an actor.
^ top
7.3.3: Bouncing Bodies
The Body class is almost the same as the prior scenario
Bodies are attracted to each other through the gravitational force of their mass
However, bodies now bounce off the edge of the screen
The method bounceAtEdge() provides the bounce effect
The act() method calls the bounceAtEdge() method
Method bounceAtEdge()
private void bounceAtEdge()
{
if (getX() == 0
|| getX() == getWorld().getWidth() - 1)
{
setLocation((double)getX(), (double)getY());
getMovement().revertHorizontal();
accelerate(0.9);
}
else if (getY() == 0
|| getY() == getWorld().getHeight() - 1)
{
setLocation((double)getX(), (double)getY());
getMovement().revertVertical();
accelerate(0.9);
}
}
Another Change
Check Yourself
The code in bounceAtEdge() that provides the actual bounce effect is ________ .
setLocation((double)getX(), (double)getY());
getMovement().revertHorizontal();
accelerate(0.9);
None of these
True or false : an positive acceleration of < 1 is deceleration.
One problem with the bounceAtEdge() method is that the body gets halfway off the screen before the bounce. What is a way to fix this issue?
^ top
7.3.4: Arranging Obstacles in Space
The Space class has two new methods:
createObstacles()
randomBodies()
The createObstacles() method creates the obstacles and assigns their sound files
The code in the method is like the initialization in the piano scenario
If we wanted to change the arrangement of obstacles, we would change this method
Random Bodies
Check Yourself
What other arrangement of obstacles would look good in the scenario?
Rewrite the loop code using a for-loop rather than a while-loop.
^ top
Exercise 7.3
In this exercise, we experiment with obstacles, gravity and music.
Specifications
Download the Newtons Lab 3 scenario file and save it in the scenario folder of Greenfoot.
Scenario file: Newtons-Lab-3.zip .
Start Greenfoot and open the scenario.
Greenfoot unzips the file for us.
Change the arrangement of obstacles so they are no longer in a straight horizontal line. For example, change the y -coordinate to a random value like:
int y = Greenfoot.getRandomNumber(getHeight());
In the Space class, add the following member variable:
private int count;
Also in the Space class, add an act() method with the following code to periodically create new bodies:
public void act()
{
count++;
if (count > 50)
{
count = 0;
randomBodies(1);
}
}
Compile and run your scenario to verify all the changes work well. Then let your simulation run for a minute and see how it evolves.
If you have problems, ask a classmate or the instructor for help as needed.
We discussed image transparency in lesson 6.2.2 . Add the following code to the act() method of Body which makes planets fade by making them more transparent:
GreenfootImage img = getImage();
img.setTransparency(img.getTransparency() - 1);
if (img.getTransparency() < 1) {
getWorld().removeObject(this);
}
Compile and run your scenario to verify the planets fade away over time.
If you have problems, ask a classmate or the instructor for help as needed.
Save a copy of your completed lesson scenario to upload to Blackboard as part of assignment 6.
As time permits, read the following sections and be prepared to answer the Check Yourself questions in the section: 7.3.5: Review .
^ top
7.3.5: Review
Answer these questions to check your understanding. You can find more information by following the links after the question.
True or false: once a simulation works well, you can "play" with it to see how changes affect the system. (7.3.1 )
When one object intersects another it is known as a _________________. (7.3.2 )
The Greenfoot method that returns an actor when objects intersect is ______________________. (7.3.2 )
When no objects intersect the method in the previous question returns ________. (7.3.2 )
Which line of the code in bounceAtEdge() provides the actual bounce effect? (7.3.3 )
setLocation((double)getX(), (double)getY());
getMovement().revertHorizontal();
accelerate(0.9);
None of these
True of false: an positive acceleration of < 1 is deceleration. (7.3.3 )
Does the following loop count up or down? (7.3.4 )
int number = 5;
while (number > 0)
{
System.out.println(number);
number--;
}
What value does the above loop first print? (7.3.4 )
What value does the above loop last print? (7.3.4 )
^ top
Wrap Up
Due Next: A5: Visualize this! (3/21/12)
A6: Visualizer Redux (3/28/12)
When class is over, please shut down your computer
You may complete unfinished lesson exercises at any time before the due date.
^ top
Home
| Blackboard
| Schedule
| Syllabus
| Room Policies
Help
| FAQ's
| HowTo's
| Links
Last Updated: April 21 2012 @23:23:51