Lecture 2 PowerPoint

advertisement
Lecture 2 Announcements
Home Computers and/or Laptops/Notebooks
By now you should have installed Java SE 8 and jGRASP on your computers, set up the
becker.jar file, and started working with some of the supplied .java files from Lecture 1.
• How many have done this successfully?
• How many have tried to do this and have still not gotten jGRASP to compile and run? If
you have your laptops with you, I will stick around for a bit after today's class to see if we
can get you up and running. I'll also stick around for a bit after next Wednesday’s class.
• I've added a TROUBLESHOOTING walk-through page to the BIT115 website if you are
getting the jGRASP wedge2 PATH error. This should be fixed with the latest version of
jGRASP, but just in case…
• IMPORTANT! Always download the .java files from the web site, save them to a local folder,
and run them from there. If you try to run them directly off the site, they go in the browser
cache and get renamed, and then things won't work!
• There are other issues to remember, which we'll cover in today's class.
• NOTE: It is essential that you get jGRASP working on your home machines or laptops if you
are going to be successful in this class (unless you are going to do all your coding on the PCs
here at the college).
Assignment Dates (By Due Date)
• Assignment 1 (LECTURE 4)
Monday, July
•
•
•
•
•
•
•
18th,
in StudentTracker by midnight
Assignment 2 (LECTURE 7)
Wednesday, July 27th
Assignment 1 Revision (LECTURE 8)
Monday, August 1st
Assignment 2 Revision (LECTURE 10)
Monday, August 8th
Assignment 3 (LECTURE 11)
Wednesday, August 10th
Assignment 3 Revision (LECTURE 13)
Wednesday, August 17th
Assignment 4 (LECTURE 15)
Wednesday, August 24th
EXTRA CREDIT (LECTURE 25)
Wednesday, August 24th
The Fickle
Finger of Fate
3
Setting Up Cascadia Email Accounts Online
https://accounts.student.cascadia.edu/
4
It's okay if right now you are feeling
somewhat overwhelmed, nervous,
confused, or just scared spitless!
• Hey! You're learning a new language (Java) and a new way of thinking about
things, so it is perfectly natural if you're feeling a bit overwhelmed right now,
or a bit nervous, or even a bit confused.
• Knowing this, we'll be taking baby steps for the next few lectures. I'll be holding
your hand and walking you through Java and code step-by-step.
• So: Do not be afraid to ask questions!
• And: Do not be afraid to come see me during my office hours (or by special
appointment) Mondays/Wednesdays 9:00-11:00am in CC3-321 or CC2-180
• Also: please email me at cduckett@cascadia.edu if you have any questions. If it
concerns code that you are working on please remember to attach the .java file
to the email so I can have a look to determine where a problem might be.
• Finally: Once I know the exact days, times, and places, going to the Open Labs
for additional one-on-one help is greatly encouraged!
5
Some Sites/Links of Interest
• Udacity – Free Online Courses
• MIT OpenCourseWare – Free Online Courses
• Coursera – Free Online Courses
• Standford Engineering Everywhere – Online CS Courses
• Academic Earth – Online CS Courses
• Khan Academy – Free Online Tutorials
• Code Academy – Interactive Code Learning
• Code School – Interactive Code Learning
• CoderDoJo – Code Club Community
• Code.org – Code Club Community
• Girls Who Code – Code Club Community
• Girl Develop It – Code Club Community
7
Lecture 2 Announcements
Reading Assignment for Today
•
•
Chapter 1.5: Types of Errors
Chapter 1.4.5 – Tracing Code
Note: there are ‘BIT 115 Student Open Source Guides’ that students wrote from previous
quarters that may deal with the various topics of your readings and lessons.
This is a great tool, and highly recommended!
8
Quarter-Long Game Plan:
• Up until the Mid-Term:
– 1st part of the quarter
Overview of topics, conceptual understanding, not as much freeform problem-solving
• After the Mid-Term:
– 2nd part of the quarter
Focus on learning and more problem-solving on your own
9
Save A Copy Of All Work
(Highly recommended!)
• In-Class Exercises, Exams, Quizzes, etc.
– If you work with someone, make sure each of you gets a copy
– For In-Class Exercises, you do not have to turn it in
• (I’ll be checking it as I walk around and watch you work)
•
If you lose track of it, and I unintentionally record it incorrectly in
StudentTracker, then whatever I’ve got will stand as the grade. Best then to
save your work for proof, if needed, in the event of a discrepancy. If you do
find a grading error in StudentTracker, then please don't hesitate to let me
know!
10
Quizzes and Exams
• Starting next lecture, you should assume that the quizzes and
exams will all be 100% pen/pencil-and-paper.
You bring the pen or pencil, I’ll supply the paper

– Start Practicing Now (My Mantra: Practice! Practice! Practice!)
• Try writing code from memory,
• and/or using Notepad or NotePad++ and then copy-and-pasting into
jGRASP to check your work
11
H
O
M
E
W
O
R
K
Assignment 1 is due LECTURE 5
Monday, April 11th
in StudentTracker by midnight
– It’s posted on the website under Assignments
– It will be due by midnight on day of Lecture 5
• If you are confused, bring your work to class, in electronic form, and
we will go over how to hand in (upload) the homework:
Student Tracker
(We’ll go over this in a moment with “Rex Winkus”)
How to Use Student Tracker (Instructions)
• If you’re stuck, seek help!
– Talk to the Instructor or a classmate or Open Lab helper
– Email me
BIT 115: Introduction To Programming
12
A Quick "Peek" at Assignment 1
Let's Have a Quick Look at Assignment 1
(so there are no unforeseen “surprises” down the road!)
Assignment 1 is due
LECTURE 5: Monday, April 11th
(uploaded to StudentTracker by midnight)
What You Need To Turn In to StudentTracker for A1
A1_Part_1.java
.java file only (no .class)
A1_Part_2.doc
MS Word .doc
A1_Part_3.doc
MS Word .doc
A1_Part_4.doc
MS Word .doc
A1_Part_5.java
.java file only (no .class)
(You'll create this from Starting_Template.java file)
Personal Data Sheet (Optional)
MS Word .doc
13
And now …. The Quiz!
NO Warm-Up QUIZ TODAY
We will have our very first 'warm-up' Quiz starting next Monday
BIT 115: Introduction To Programming
14
StudentTracker Reminder
15
Today’s Topics
• Dissecting the Code: What it means and what it does
– opening and working with .java Files
– jGRASP: Another Look
• Errors: How to find and fix them
• How to set up a City
• Tracing Code
– Predicting What A Program Will Do BEFORE you Run It
• Important Java and OOP Terms
– like Class, Object, Method, Parameter, etc
BIT 115: Introduction To Programming
16
Dissecting the Software
Dissecting the Code
17
What Happened When You Installed Java
Java Virtual Machine (JVM)
Consists of Many Different Components (Classes) That Allow
Java Programs to Do Different Things
http://www.javacoffeebreak.com/articles/inside_java/insidejava-jan99.html
18
What Happened When You Installed Java
http://docs.oracle.com/javase/1.5.0/docs/api/index.html
19
What Happened When You Installed jGRASP
20
What Happens When You Add Becker.Jar to
jGRASP Path
21
What Happens When You Add Becker.Jar to
jGRASP Path
http://www.learningwithrobots.com/doc/
22
Downloading and Working On .java Files
Important
Always download the .java files from the web site first to a folder on your computer or USB thumb
drive before opening and working on them. If you work on files from the browser cache, the file names can be
changedUnder
and then the class name will no longer match up and your programs won’t run correctly. Also the
browser cache likes to append numbers to the file name if you have already downloaded that file previously,
which also means the class name won’t match the file name.
Course Wide Information
.java Files Should Be Associated to jGRASP
If you have the Java JDK and jGRASP properly installed, the .java files you download from the BIT115
web site should be associated with jGRASP. This means they will appear with with jGRASP “G” icon.
Typically, all you have to do to open a .java file is to simply double-click on it and it will open
automatically in jGRASP.
Alternatively, you can open jGRASP and select the file from the menu bar through File > Open or else to the
simply drag-and-drop the file into the work window.
23
Two Types Files for a Compiled Program: .java and .class
When you write a Java program, you will do so a GUI* Java compiler like jGRASP which
also doubles as an IDE**
When writing Java and saving Java code you do so in a .java file which is a basic text file.
It contains “human readable” text code…at least it is readable for some humans .
When you compile your Java code into a working Java program, it creates a .class file
which is what the computers uses to line everything up in memory and to run the
program. It does not consist of human readable text, but rather machine code or byte
code.
The reason that each of your .java files are built inside of “classes” in the code are so your
computer can find and run the program after it is compiled, since the class files that are
created contain language only the computer understands.
So, in other words, a ‘class’ is another name for the idea of a ‘mini-program’ which only
becomes ‘real’ (in the virtual sense) once the program is successfully compiled.
* Graphic User Interface
** Integrated Development Environment
Another Look
25
Dissecting the Code:
What It Means and What It Does (Quiz2.java)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import becker.robots.*;
public class Quiz2 extends Object
{
public static void main(String[] args)
{
City toronto = new City();
Robot Jo = new Robot(toronto, 0, 3, Direction.NORTH, 0);
new
new
new
new
Thing(toronto, 2, 2);
Wall(toronto, 3, 3, Direction.EAST);
Wall(toronto, 3, 3, Direction.NORTH);
Wall(toronto, 3,3, Direction.SOUTH);
Jo.turnLeft();
}
}
Let’s download and run the Quiz2.java program to see what it does, and then we will go
over all of the parts of its code line-by-line and discuss what it means.
import becker.robots.*;
becker.jar
This imports from the becker.jar collection all the classes contained in the
robots file so they would be functionally available in Java (JDK) and any code
written using it. These classes include the Robot.class, the Thing.class, the
City.class, the Wall.class, and over a hundred more.
NOTE: Java loads some
classes by default into the
compiler, while others it does
not. Later on we will have to
import
additional
Java
classes in our code to get our
programs to work
http://www.learningwithrobots.com/doc/
29
public class Quiz2 extends Object
public
class
Quiz2
extends
Object
'public' so other classes can use it if need be.
a 'class' is a blueprint for making
'objects' that can do something
'Quiz2' is the name of the class. It can be any name
(but must match file name if it contains main). The
program uses this name when it runs to know what
'objects' and 'methods' to use in the program.
Java, like other object-orientated languages, supports
class inheritance. Inheritance allows one class to "inherit"
the properties of another class. For example, all Java
objects are inherited from the java.lang.Object class
which is a fundamental part of Java and the Java
libraries. Our Quiz2 class is inheriting the properties of
Java's Object class, and so extends its actions and
attributes in the program hierarchy.
http://www.tutorialspoint.com/java/java_object_classes.htm
30
Note: main is a method() inside a Class
public static void main(String[ ] args)
The method is public because it is accessible to the JVM (Java Virtual Machine) to begin
execution of the program, and can be accessed by any other class or method.
The static keyword signifies the fact that this method can be invoked without creating an
instance of that class (an object). Main is called before any objects are made, hence static.
void signifies that this method does not return anything. In other words no new or altered
data is sent out from it for use by the rest of the program. Nothing is returned, so void.
Just like in the C “procedural” language and other languages, this is the main method in a
Java program. When you run a Java program, execution begins in the main method.
String is the data type that could be passed to the method, although no data type needs to
be passed. An example of a data type is an int or float. The [] represents unknown quantity.
args is the name of the parameter. We can pass any number of arguments to this method.
31
City toronto = new City();
Names the object

Creates the new City object
We want to make a new instance of the City class (City.class) found in the becker > robots
directory (inside becker.jar) and call this new object Toronto
The City class contains all the attributes and actions necessary to set up a city when a named
city object (like toronto) is created, include shape, size, color, streets, avenues, etc.
By itself, the City class can't do anything. It's just a collections of ideas and concepts. You
need an object made from the City class (like toronto here) to actually do something with a
city.
NOTE:
In Java, '=' is an assignment operator, and points right to left; "==" is an equals
sign.
EXAMPLE:
x = 1 assigns 1 to variable space x and x == 1 means x equals 1.
32
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import becker.robots.*;
public class Quiz2 extends Object
{
public static void main(String[] args)
{
City toronto = new City();
Robot Jo = new Robot(toronto, 0, 3, Direction.NORTH, 0);
new
new
new
new
Thing(toronto, 2, 2);
Wall(toronto, 3, 3, Direction.EAST);
Wall(toronto, 3, 3, Direction.NORTH);
Wall(toronto, 3,3, Direction.SOUTH);
Jo.turnLeft();
}
}
33
Now what about the Robot line of code? What does that
all mean?
Robot Jo = new Robot(toronto, 0, 3, Direction.NORTH, 0);
The best way to figure this out is to have a look at the Becker Library which gives us
information about that becker.jar file we are associating with our programs. Referencing the
Becker Library will help us to know how the objects of the Robot class are setup and what
methods they can use.
Let’s have a look at the Becker Library!
34
Becker Robot Library
Using it to determine class setup and method use
In the BIT115 website, under the LIBRARIES & SPECIFICATIONS heading, click on the
Becker Robot Library link.
This link takes you to the Becker Libraries located at:
http://www.learningwithrobots.com/doc/
Robot Jo = new Robot(toronto, 0, 3, Direction.NORTH, 0);
35
In the upper left-hand column, select becker.robots, then in the lower left-hand
column select Robot to bring up information about the Robot class
In the right-hand column, scroll down to the Constructor Summary section. You will
see that there are two types of “constructor” types available for the construction of a
Robot object from the Robot class, one that uses four (4) slots and one that uses (5)
slots.
The four-slot constructor is used when you want to create a Robot object that does
not need to work with things (either pick up things or put down things).
The five-slot constructor is used when you want to create a Robot object that does
work with things (either pick up things or put down things).
So what do the four- or five-slot constructors represent? Let’s see on the next slide 
Not to worry: we will talk about “constructors” and how they work in Lecture 3.
The four-slot constructor is used when you want to create a Robot object that does
not need to work with things. It has four slots for the City name, Street location,
Avenue location, and Direction facing
The five-slot constructor is used when you want to create a Robot object that does
work with things. It has four slots for the City name, Street location, Avenue location,
Direction facing, and Number of Things in its Backpack.
Again: we will talk about “constructors” and how they work in Lecture 3.
So, when we see a line of code like this, it is showing us that we are using the 5-slot
constructor:
Robot Jo = new Robot(toronto, 0, 3, Direction.NORTH, 0);
Again: we will talk about “constructors” and how they work in Lecture 3.
Robot Jo = new Robot(toronto, 0, 3, Direction.NORTH, 0);
Names the Robot  Creates the new Robot using five parameters
•
•
•
•
•
•
Our instance of the Robot object is named Jo
Jo is placed in a City called Toronto
Jo is starting out on Street 0
Jo is starting out on Avenue 3
Jo is starting out facing North
Jo is starting out with 0 (zero) Things in its backpack
Now, another way to "construct" this is with only four parameters, by leaving on the number
of Things in the backpack
Robot Jo = new Robot(toronto, 0, 3, Direction.NORTH);
If you are not going to be picking up or putting down Things in your program, then you can
"construct" your Robot without this fifth 'backpack' parameter.
Later on, when we start creating our own types of Robots and methods, some of the ICES will
be set up in such a way that parts of the code will use five parameters and other parts of the
code will use four parameters and this will cause an error. We'll go over this in greater detail
when the time comes.
http://www.learningwithrobots.com/doc/
40
new
new
new
new
Thing(toronto, 2, 2);
Wall(toronto, 3, 3, Direction.EAST);
Wall(toronto, 3, 3, Direction.NORTH);
Wall(toronto, 3, 3, Direction.SOUTH);
These will work by default. For stuff that just sits there, we don’t have to actually
give them unique names (e.g., BrickWall) but we can’t talk about them in code,
however a Robot can pick up/put down an unnamed object. Why would you want
to give a wall a unique name?
If you look at the becker library you will discover that Wall actually extends Thing,
that is to say Wall has inherited all the initial properties of Thing
Jo.turnLeft();
turnLeft() is one of the methods of the Robot class, along with move(),
pickThing(), putThing(), frontIsClear(), countThingsInPackback(), and
several more. Because Robot can turn left, Jo can turn left.
BIT 115: Introduction To Programming
41
Something to Remember:
In parameter order, street comes first
and avenue comes second.
Streets go West-East (left-right)
Avenues go North-South (up-down)
A neat trick to remember the difference
is to recall that the 'A' and 'V' in Avenue
point up and down.
Three Types of Errors
43
Chapter 1.5: Types of Errors
3 Different General Categories of Errors:
 Compile-Time Errors (or Syntax Errors)
 Run-Time Errors (or Application Errors)
 Intent Errors (or Logical Errors)
44
An Historical Side Trip:
Why Are Bugs Called Bugs?
Use of the term "bug" to describe inexplicable defects has been a part of engineering
jargon for many decades and predates computers and computer software; it may have
originally been used in hardware engineering to describe mechanical malfunctions. For
instance, Thomas Edison wrote the following words in a letter to an associate in 1878:
It has been just so in all of my inventions. The first step is an intuition, and
comes with a burst, then difficulties arise — this thing gives out and [it is]
then that "Bugs" — as such little faults and difficulties are called — show
themselves and months of intense watching, study and labor are requisite
before commercial success or failure is certainly reached.
In 1946, when computer pioneer Grace Hopper joined the Harvard Faculty at the
Computation Laboratory to work on the Mark II and Mark III computers. Operators traced
an error in the Mark II to a moth trapped in a relay, coining the term “bug.” This bug was
carefully removed and taped to the log book. Stemming from the first bug, today we call
errors or glitches in a program a bug.
45
46
Compile-Time Errors (or Syntax Errors)
Anything that goes wrong when you compile the file is a compile-time error!
Point out that the Output Panel is often small, but it can be resized, and you should get
used to figuring out which line the error pertains to.
Java is case sensitive
- Java is different from java, is different from JaVa
- This means you must type in names, etc, EXACTLY the same
File name MUST be the same as the class name that has the main method
You need the import becker.robots.*; at the top of each robot file
Forgetting to Compile BEFORE Running
- You need to compile the file EVERY SINGLE TIME you change it
- You should also wait UNTIL the compilation finishes BEFORE trying to run it
Strategy For Fixing Compile-Time Errors:
Follow the debugging strategy (listed in your text) to find and correct the syntax errors in
the FindErrors.java program later this evening when you do your In-Class Exercises.
1. Compile the program to get a list of errors;
2. Fix the most obvious errors, beginning with the first error reported
3. Compile the program again to get a revised list of the remaining errors.
47
Run-Time Errors (Application/Crashing Errors)
Anything that causes the program to crash while it's running. If you encounter a run-time error
when you are compiling and running your Java programs, then this would be a jGrasp problem, or
a Windows Operating System problem, and NOT a Java Problem. The Java language does a lot to
protect you from this type of error, so you shouldn't see many of these.
Intent Errors (Logical Errors)
The program compiles and runs without crashing, but it doesn't do what you want it to.
Example:
- Robot takes an extra leftTurn, and runs off the screen
- Robot doesn't pick up a Thing when it's supposed to.
- Robot collides with a Wall (the book calls this a run-time error, but it technically isn’t)
As you continue learning to code you'll make fewer "typo" type mistakes, and end up with more
Intent errors then Compile-Time errors.
You need to come up with a personal strategy to figure out where the Intent problems are, and
how to fix them. One Option: Use a Program Debug Table (show where this is on web site)
48
Lecture 2 ICE:
Finding And Fixing Errors In Your Program
•
•
In-Class Exercise Directions 2.1
FindErrors.java
Program Debug Table
We'll Wait and Do All the ICEs
Together at the End of Lecture
BIT 115: Introduction To Programming
49
Lecture 2 ICE: Setting Up a City
•
•
In-Class Exercise Directions 2.2
Starting_Template.java
We'll Wait and Do All ICEs
Together at the End of Lecture
BIT 115: Introduction To Programming
50
Chapter 1.4.5 – Tracing Code
BIT 115: Introduction To Programming
51
BIT 115: Introduction To Programming
52
BIT 115: Introduction To Programming
53
Important Terms to Remember
54
Some Important Terms To Remember
A class is a set of functions that can work together to accomplish a task. It can contain or manipulate
data, but
it usually does so according to a pattern rather than a specific implementation. An instance of a
Under
class is considered an object. Until an object is instantiated from a class, the class can’t actually do anything.
Course Wide Information
An object receives all of the characteristics of a class, including all of its default data and any actions that
can be performed by its functions. The object is for use with specific data or to accomplish particular tasks.
A method simply refers to a function that is encased in a class. It usually entails an action.
A parameter is a variable that is passed into a function that instructs it how to act or gives it information
to process. Parameters are also sometimes called arguments.
A field or property is a default set of data stored in a class. A class can have multiple properties and
can be changed dynamically through the methods of the class. These are sometimes called attributes.
Inheritance is one of the keys that make OOP tick. Simply put, classes can inherit methods and fields
from other classes by extending them and each class can be extended by multiple classes. This means that
you can start with a base (or parent) class that contains shared characteristics among several classes. That
base class can then be extended by other classes (children) that are similar but are meant for slightly
different purposes. Any changes in the parent class will automatically cascade to its children.
BIT 115: Introduction To Programming
55
Class (The “Idea” of Attributes and Actions, Features and Functions)
A class is a collection of functions that can work together to accomplish a task. It can contain or manipulate
data, but
it usually does so according to a pattern rather than a specific implementation. An instance of a
Under
class is considered an object. Until an object is instantiated from a class, the class can’t actually do anything.
Course Wide Information
Example
The Robot class. The Robot class contains all the attributes and actions that a robot might
have once it is created (or instantiated) as an object. Until then, all the Robot features and
functions are just the idea how a robot might work, but being an idea the class doesn’t do any
work itself. So, a class is like a blueprint, and an object is what is built from the blueprint.
http://www.learningwithrobots.com/doc/
Just like we might have an idea how a car should look and operate—body, engine, four tires,
steering wheel, gas and brake pedals, etc—an idea of a car is not the same of an actual
working car. Here the idea of a car is a class, and an actual working car is an object.
BIT 115: Introduction To Programming
56
"Brakes"
"Engine"
"Lights"
"Transmission"
"Wheels"
"Chassis"
"Seats"
"Power"
"Car" Class
"Car" Object
57
"Brakes"
"Engine"
No "Wings” Here
"Lights"
"Transmission"
"Wheels"
"Chassis"
"Seats"
"Power"
"Car" Class
"Car" Object
58
Object
(An Instance of the “Idea” Made Actionable)
An object receives all of the characteristics of a class, including all of its default data and any actions that
Under by its functions. The object is for use with specific data or to accomplish particular tasks.
can be performed
Course Wide Information
Example
When we create an object from the Robot class we do so by creating a named instance of the
Robot class that will possess all the features and functions that were outlined as belonging to
the Robot class as an idea. Once the object is instantiated, what was once the idea of a Robot
now becomes an actual Robot that possesses specific ‘Robot’ properties (its shape, size, color,
speed) and that can perform specific ‘Robot’ actions (like move, turn left, put down a thing,
pick up a thing, etc).
http://www.learningwithrobots.com/doc/
BIT 115: Introduction To Programming
59
Method
(An “Action” That Might Be Performed by the Object)
A method simply refers to a function that is encased in a class. It usually entails an action.
Example
After we have created a named object from the Robot class that possesses all the properties
(or attributes) belonging to robots, the robot can now perform some kind of action or actions
(like move, turn left, put down a thing, pick up a thing, etc). These actions are the methods
belonging to the Robot classes, and which an instance of the Robot class can perform. A robot
can move because the Robot class has a method called move() which will allow the robot to
move one space forward each time it is called upon to do so.
Although we might want the robot to mix a martini, the robot can not because the Robot class
does not contain a mixAMartini() method. Later on in this course we will learn how we might
make a new kind of class that could contain a mixAMartini() method, but the Robot class we
are using now does not have just such a method.
http://www.learningwithrobots.com/doc/
BIT 115: Introduction To Programming
60
Parameter (“Information” or “Instruction” That Might Be Given)
A parameter is a variable that is passed into a function that instructs it how to act or gives it information
Under
to process.
Parameters are also sometimes called arguments.
Course Wide Information
Example
When we have a robot object call upon a method in order to perform some action, that
method may or may not take a parameter which is an additional piece of information or an
instruction that might extend its functionality.
Currently most of the methods belonging to the Robot class do not take any parameters
(although in a moment we’ll look at a Robot method that does take a parameter). For
example, the move() method when called upon will allow the robot to move one space
forward. You’ll notice that the move() method has two “empty” parentheses which represents
that it doesn’t take a parameter. Had the programmer of the Robot class designed the move()
method differently, then it might have taken a parameter to represent how many places the
robot should move. For example move(1) might make the Robot move one space forward,
move(2) might make the Robot move two spaces forward, move(3) might make the robot
move three spaces forward, and so on. Since the programmer did not design the move()
method this way, using the move() method like this will not work. This was only a theoretical
example.
http://www.learningwithrobots.com/doc/
61
Field or Property (The “Attributes” of Class and Its Objects)
A field or property is a default set of data stored in a class. A class can have multiple properties and can
Under
be changed
dynamically through the methods of the class. These are sometimes called attributes.
Course Wide Information
Example
When we create a named instance of a robot from the Robot class, this robot object comes
with a set of predefined properties and attributes. For example, by default the new robot
object is so many pixels high and so many pixels wide, its shape is an arrowhead, its color is
red, and its location and placement and direction in the City is defined by the parameters that
were passed to it (which we will discuss in the next Dissecting the Code section).
For example, one of the properties of the Robot class is that a robot will move one space
forward in .5 seconds. This speed, .5 seconds, is a pre-defined property of the Robot class and
any instances of objects made using the Robot class.
Now these pre-defined properties might be changed dynamically while the program is running
if just such a feature was developed programmatically to do so. In the case of the robot’s
default speed of .5 seconds for every move, there is a setSpeed() method which can be used
to change the robot’s initially defined speed. For example setSpeed(4) will move the Robot
twice as fast (the default speed is 2).
http://www.learningwithrobots.com/doc/
62
Inheritance (Extending a Class’s Features to a New Class )
Inheritance
is one of the keys that make Object-Oriented Programming tick. Simply put, classes can
inherit methods and fields from other classes by extending them and each class can be extended by multiple
classes.Under
This means that you can start with a base (or parent) class that contains shared characteristics
among several classes. That base class can then be extended by other classes (children) that are similar but
are meant for slightly different purposes. Any changes in the parent class will automatically cascade to its
children.
Course Wide Information
Example
We will learn about inheritance and how to put it to good use next week. A brief example
what inheritance is can be explained by looking at our Robot class. Right now the Robot class
has a turnLeft() method but it does not have a turnRight() method. If you created a Robot
object and wanted it to turn right then you would have to call upon it to turn left three times!
Now we might create a new type of Robot class (perhaps called MrRoboto) that would extend
all the features and functions of the Robot class (like move(), turnLeft(), etc) and also create its
own new set of methods (like turnAround(), turnRight(), etc). In this example we are using the
original Robot class to create our new MrRoboto class, and as such the MrRoboto class is
inheriting all the original features and functions of the Robot class. This is a great tool of
Object Oriented Programming (or OOP) because this means the programmer doesn’t have to
code all the Robot class features and functions from scratch to use in the new MrRoboto class.
All the programmer has to do is code the new methods (like turnAround() or turnRight())
since the MrRoboto class inherited all the original methods (like move(), turnLeft(), etc).
63
PREVIEW: Extending a Class
This is important stuff, so we will be going over
it twice – once today as a “preview” and again
during the next lecture (Lecture 3) with an
accompanying ICE.
64
Constructor
Here, when we create a new instance (an object) of the Robot class, a ‘hidden’ default
constructor works in the background to make sure that Kelsey inherits all the attributes and
methods available to Robots, including its placement on a particular Street and Avenue and
Direction in a particular City, and that it can use all of the actions (methods) available to the
Robot class (including move(), pickThing(), turnLeft(), putThing(), frontIsClear(), etc.)
http://www.learningwithrobots.com/doc/
BIT 115: Introduction To Programming
65
Constructor
Constructors have one purpose in life. To create an instance of a class. This
can also be called creating an object, as in:
The purpose of a method, by contrast is much more general. The purpose of a
method is to execute Java code, to allow the object to do something.
BIT 115: Introduction To Programming
66
BIT 115: Introduction To Programming
67
Now … what if these is an action that you might want Kelsey to do that isn’t
found in the Robot class?
For instance, instead of invoking the the turnLeft() method three times, you
could just call up a turnRight() ?
The problem is, the Robot class does not have a turnRight() command
(method). The Robot class has been finalized. You cannot add to it.
The good news is, you can create a new method like turnRight() that will do
what you want the robot to do!
But in order to make this happen, you need to extend the Robot class …
BIT 115: Introduction To Programming
68
Extending a Class:
Where ClassB extends ClassA
In Plain Ol’ English: Where ClassB “inherits” the attributes and actions of ClassA
… then adds new functionality to them.
When we’re not interested in extending a class because we’re happy with the
methods that come with that class just the way they are, then we declare our class the
‘normal’ default way: public class Example extends Object
Object is the top class of all class hierarchies. When a new
instance of anything is made in Java, then it inherits all the
attributes and actions of the Object class. You can’t get a new
object without Object.
Object
Class
Hierarchy
However, if we want to add new functionality (methods) to the Robot class (like
turnRight) then we need to extend the Robot class (which is itself an extension of
Object)
public class MrRoboto extends Robot
BIT 115: Introduction To Programming
69
Extending a Class:
Where ClassB extends ClassA
Instance vs. Extension?
Instance creates a new object from a class, but extension extends a new
class from a class through inheritance, allowing for an improved class that
might offer additional attributes and services (methods) not available in the
original class …
BIT 115: Introduction To Programming
70
Extending the Robot Class
public class MrRoboto extends Robot
MrRoboto
extends
inherits
Robot
MrRoboto “inherits” all of
the Robot attributes and
services and then can have
additional attributes and
services of its own (i.e.,
those not shared by Robot).
BIT 115: Introduction To Programming
71
Superclass and Subclass
Robot
Superclass
MrRoboto
Subclass
BIT 115: Introduction To Programming
72
Constructor
import becker.robots.*;
public class MrRoboto extends Robot
{
public MrRoboto(City theCity, int street, int avenue, Direction aDirection)
{
super(theCity, street, avenue, aDirection);
}
//New service or services go here
}
BIT 115: Introduction To Programming
73
Constructor
import becker.robots.*;
public class MrRoboto extends Robot
{
// This declares the parameters used by Robot “inside” of MrRoboto
public MrRoboto(City theCity, int street, int avenue, Direction aDirection)
// This passes on information received by the parameters used by Robot ‘inside” of MrRoboto
{
super(theCity, street, avenue, aDirection); //Instead of Robot here, Java uses the keyword super
}
//New service or services go here
}
Constructors fulfill a special roll. They are responsible for ensuring an object is set up properly when
it is created, and that it can be immediately used once it is created. This construction process is
known as initialization. Two other details about constructors: they must have the same name as the
class and they do not have a return type, not even a void.
NOTE: We will talk briefly about return types in just a few minutes, and go over them in greater detail in an upcoming
lecture.
BIT 115: Introduction To Programming
74
Constructor
public class MrRoboto extends Robot
{
public MrRoboto(City theCity, int street, int avenue, Direction aDirection)
{
super(theCity, street, avenue, aDirection);
}
}
MrRoboto
Robot
BIT 115: Introduction To Programming
75
Constructor
public class MrRoboto extends Robot
{
public MrRoboto(City theCity, int street, int avenue, Direction aDirection)
{
super(theCity, street, avenue, aDirection);
}
}
MrRoboto
Robot super
BIT 115: Introduction To Programming
76
Constructor
public class MrRoboto extends Robot
{
public MrRoboto(City theCity, int street, int avenue, Direction aDirection)
{
super(theCity, street, avenue, aDirection);
}
}
MrRoboto
 imagine a conduit …
super
BIT 115: Introduction To Programming
77
Constructor
public class MrRoboto extends Robot
{
public MrRoboto(City theCity, int street, int avenue, Direction aDirection)
{
super(theCity, street, avenue, aDirection);
}
}
bothell, 3, 2, Direction.SOUTH
MrRoboto
super
BIT 115: Introduction To Programming
Since MrRoboto is inheriting the
Robot parameters, the Robot still
needs those parameters in order
for MrRoboto to inherit them.
This is why it appears as if there
are two sets of parameters: one
set to pass through MrRoboto, a
second set for Robot to receive
them, where Robot sends them
back to MrRoboto by extension.
78
Adding New Services
public void turnAround()
{ this.turnLeft();
this.turnLeft();
}
public void move3()
{ this.move();
this.move();
this.move();
}
.
public void turnRight()
{ this.turnAround();
this.turnLeft();
}
79
The this keyword
The new Java feature in the new services we created is the use of the
this keyword.
The keyword this is useful when you need to refer to an instance of the
class from its method, but without having to refer to it by a specific
name. Why? Because when you create the new method, you don’t
know the name of the particular robot that is going to use it, so ‘this’ is
a kind of placeholder name.
The this keyword helps us to avoid name conflicts, and also creates a
shortcut to having to invent a unique name for each field in the
different methods.
public void turnAround()
{ this.turnLeft();
this.turnLeft();
}
80
Putting It All Together
Two Ways of Doing the Same Thing
Version 1: One Class
MrRoboto.java
Version 2: Two Classes
MrRobotoMain.java
81
Putting It All Together
MrRoboto2.java
MrRoboto.java
MrRobotoTest2.java
All on One File
On Two Separate Files
82
Lecture 2 ICEs
Now: We will do all the Lecture 2 In-Class Exercises in this order:
•
•
•
In-Class Exercises 2.1
In-Class Exercises 2.2
In-Class Exercises 2.3
Work on these ICEs to the End of Class Time
IMPORTANT! CityFrame – An older version of becker.jar file contained
a class called CityFrame which when used looked something like this:
CityFrame City = CityFrame(seattle);
Please ignore any reference to this. It will, however, rear its ugly head in the ICEs on
purpose as an example of old 'legacy' code that should either be "commented out"
or deleted altogether since it will not allow the program to run correctly!
83
Download