slides - Angus Forbes
Download
Report
Transcript slides - Angus Forbes
CS 5JA Introduction to Java
note...
You must use your umail email when you submit homework. In fact every
time you email me or any of the TAs you should use your umail
account.
From now on, all late assignments are due by Tuesday at 11am. This is
because I will discuss the previous week’s homework in class.
Grades from the homeworks are will be posted on the course website. The
link will be on the original homework page, indexed by your secret code
(which you should all have gotten by now.)
If anyone doesn’t see their grade, or gets an erroneous grade, see me as
soon as possible so we can resolve the situation.
CS 5JA Introduction to Java
On Thursday...
Last class we talked about a few different things:
We looked at the while loop and the for loop which allow you to loop (or
iterate) over a chunk of code.
We talked about how the loops check to see if particular conditional
evaluates to true to decide if it should keep looping.
We talked about the break statements to exit a loop abruptly; and we
talked about the continue statement which brings you back to the top of the
loop without evaluating any lines beneath it.
We talked about how to join together logical operations to simplify
conditionals.
And finally, we took a close look at two classes that we used to model an
ATM machine and a couple of bank accounts.
CS 5JA Introduction to Java
Today...
The classes Account.java and AtmMachine.java are the basis of your
homework, and some people asked me to talk about the concept of
classes and object some more.
Then we’re going to look at one last control statement, the switch
statement. This is the last concept that you will need to absorb for the
midterm exam, which will take place during class next Tuesday.
Then we will look at a super basic graphics function that we can get by
extending the JPanel class and overriding its paintComponent method..
And then we’ll talk a bit more about methods, and talk about the scope of a
variable.
CS 5JA Introduction to Java
A Class - Summary
What is a class?
a) It groups together some pieces of data.
b) It contains specific instructions you can use to interact with that data
The data are called instance variables.
The instructions are called methods.
In general, you want to use classes to model some aspect of the system
you are trying to model. So you need to ask yourself: what parts of the
system can be separated out? This is usually a natural process. Humans
automatically see things in terms of usable objects. Moreover, humans
think in terms of classes of objects.
CS 5JA Introduction to Java
A Class - Summary
For instance, if you want look at a bicycle, you will notice that it is made up of
different parts: wheels, handle bars, a seat, pedals, and a frame that holds it
together. So you might say a bike is composed of other objects.
Also you can recognize that there are lots of different types of bicycles, but that
they are share similarities. The similarities are: a) that they are all made out of the
same basic objects, and b) that they are all used for the same function.
Moreover, the basic object themselves are made out of more basic objects, and
you can recognize that there are lots of different versions of those basic objects, in
fact, you might say that there are a “class” of objects with a certain function, made
up of certain things. For instance, there are tons of different bike cranks out there.
But all cranks have pedals attached to them, and they all spin, etc. They all have a
similar shape. They are all made of smaller parts: nuts, bolts, metal, etc. And they
all have the same function.
So if you were programming a bicycle, you might naturally break it into different
classes
CS 5JA Introduction to Java
A Class - Summary
So if you were programming a bicycle, you might naturally break it into
different classes.
You might have a top-level Bike class. What data would be important to
describe the bike? What instructions would need to exist for you to use the
bike?
CS 5JA Introduction to Java
A Class - Summary
So if you were programming a bicycle, you might naturally break it into
different classes.
You might have a top-level Bike class. What data would be important to
describe the bike? What instructions would need to exist for you to use the
bike?
data: smaller objects it is composed of (wheels, frame, handlebars, etc) ;
owner of bike; price; brand; type (mountain bike, road bike, bmx);
maximum speed, etc
instructions: mountBike; rideBike; ringBell; doWheelie; whatever...
And what data and instructions would be appropriate in defining a bike
wheel?
CS 5JA Introduction to Java
A Class - Summary
And what data and instructions would be appropriate in defining a bike
wheel?
data: composed out of spokes, rims, tubes; maximum air pressure; name;
brand; resistance to glass and nails; radius of wheel; etc
methods: fillWithAir; deflate; applyBrakes; etc.
Note that all the objects have certain things in common: they all share
certain types of data and certain methods to interact with the data.
But the specific way in which that that data is defined, and the specific
things that happen when you interact with the data is what makes your
object unique.
CS 5JA Introduction to Java
A Class - Summary
You can also model things which are inherently abstract. For example, in
our homework, we have a class called “Account” stored in a file called
“Account.java”. Now an account isn’t generally a physical thing (unless it’s
a piggy bank), but it still has certain properties and methods of interacting
with it that define it as an account.
What data is fundamental to an account?
What data is important to an account?
What actions are needed to manipulate this data?
In other words, what is the least amount of definition needed to define an
account, both in terms of data and in terms of instructions?
CS 5JA Introduction to Java
A Class - Summary
Data:
the balance; the type of account; the bank the account is for; the branch it
was opened in; the date it was first created; a history of all transactions;
the limit on how much a person an take out per day; the number of bonus
points/miles you get each time you add money; the amount of interest you
get; the amount that gets deducted if you have less than a certain amount,
etc, etc...
Methods:
check balance; add bonus points; store transaction information; save
branch information; accrue interest; alert bank manager of suspicious
activity; restrict withdrawals; increase/decrease balance, etc, etc...
CS 5JA Introduction to Java
Objects - Summary
Once you have defined a class, you need to instantiate it in order to use it. The
instantiation makes it a unique, real “thing”. It’s the difference between saying: A
bicycle has wheels, and can go a certain speed, and has a certain size, a certain
color and saying: I have a Trek 900 Hybrid-style bike with a 22” frame, colored
blue, with low-end Shimano brakes...
All classes have a default constructor. You define your own constructor when you
want to automatically initialize your data.
For example, in the Account class that your homework is based on, the constructor
requires an initial account type and an initial balance.
This is because we defined the constructor with the following signature:
public Account(String accountType,
double startingAmount)
When you instantiate the Account class you need to provide the constructor with
this data. The signature is like a contract. If you break the contract, your program
will not compile. Just like if you break the law, you will go to jail.
CS 5JA Introduction to Java
Objects - Summary
You instantiate an object using the new keyword.
Since our constructor has a signature asking for a String and then a double, we
must instantiate our object of type Account with this data, in this order:
String type = “checking”;
double balance = 500.0;
Account checkingAccount = new Account(type, balance);
Now we have created (or instantiated) an object named checkingAccount of type
Account. This account’s instance variables are initialized in its constructor so that
checkingAccount’s “balance” equals 500.0 and “type” equals “checking”. These
variables are the arguments or parameters you pass to the constructor.
Now we are able to manipulate the data using the methods we defined for the
Account class.
CS 5JA Introduction to Java
Objects - Summary
Just as the constructor we made has a signature, the methods we define also have
a signature. To use these methods, you are required to adhere to the letter of the
law! Here’s a method from Account.java:
public void setBalance(double amount)
{
balance = amount;
}
This method lets you update the balance to a new value. If you want to instruct the
object to update its balance, you are required to pass in a double. If you pass in
nothing, or any other type of data then you will get an error!
Remember, balance is an instance variable (which we initialized in the constructor).
The variable amount is a local variable which is defined only during the life of the
instruction. Once the code is done with the method (ie, all the lines within the
squiggly brackets) we throw the variable amount into the garbage. Here we assign
whatever is in the local variable amount to our instance variable balance. The
variable balance will not be thrown away.
CS 5JA Introduction to Java
Objects - Summary
Here’s another method from Account.java:
public double getBalance()
{
return balance;
}
This method lets you retrieve the balance. If you want to instruct the object
to retrieve its balance to you, then you are required to pass in nothing. If
you pass anything at all then you will get an error. That is your end of the
bargain. The object’s end of the bargain is defined in the second keyword
of the method signature. Here that keyword is double. The object will
return some data to you, and that data will a decimal number. You can see
that no instance variables are altered. The only thing that happens is that
you now have a bucket containing the value of the instance variable
balance. And you can do whatever you want with it. For example
AtmMachine prints it to the screen when you select the “check balance”
from the menu.
CS 5JA Introduction to Java
Summary
To summarize, a class has :
instance variables,
methods,
a constructor.
You instantiate an object with the new keyword and by passing in the
parameters required by the constructor’s signature.
You invoke the methods of your object using the dot notation and passing
in the parameters required by the method’s signature.
Account myAccount = new Account(“new account", 1000.0);
myAccount.setBalance(myAccount.getBalance()-5.0);
CS 5JA Introduction to Java
questions???
CS 5JA Introduction to Java
Switch
A switch statement is similar to an if statement. It simplifies certain types of
selections. It selects a code block based on a simple conditional.
switch(scanner.nextInt())
{
case 1:
System.out.println(“how much to withdraw?”);
withdrawMoney(scanner.nextDouble());
break;
case 2:
System.out.println(“how much to deposit?”);
depositMoney(scanner.nextDouble());
break;
case 3:
checkBalance();
break;
default:
System.out.println(“This is not a valid option!”);
}
CS 5JA Introduction to Java
Switch vs If..else
int choice = scanner.nextInt();
if (choice == 1)
{
System.out.println(“how much to withdraw?”);
withdrawMoney(scanner.nextDouble());
}
else if (choice == 2)
{
System.out.println(“how much to deposit?”);
depositMoney(scanner.nextDouble());
}
else if (choice == 3)
{
checkBalance();
}
else
{
System.out.println(“This is not a valid option!”);
}
CS 5JA Introduction to Java
Switch
The most important thing to remember about the switch statement is that you need
to remember the break statement at the end of each case or the code will continue
on to the next case! (In some instances, this is exactly what you want).
int val = 1;
switch(val)
{
case 1:
System.out.println(“I am here!”);
case 2:
System.out.println(“Oops! I am here too!”);
break;
default:
break;
}
Although the switch statement is not as prevalent as the if...else statement, it does
simplify certain code and you will run across it often.
CS 5JA Introduction to Java
Switch
The conditional is always simple. It is always a comparison of an int variable to a
number.
double decimal = 1.5;
switch(decimal) {} //Error!
boolean truth = true;
switch(truth) {} //Error!
The case statements are shortcuts for the comparison of the int variable after the
switch keyword to an int constant. That is an actual number and NOT a
variable.
int valA = 1, valB = 2;
switch(valA)
{
case valB: //ERROR!!!
...
CS 5JA Introduction to Java
Static?
If you add the static keyword to an instance variable or a method, that
means that you can access that method/variable without instantiating the
object. “Static” here means “unchanging”. That is, there is only one copy of
this method/variable for ALL objects of this class.
Basically, unless you have a reason to do this, it is best that you do not use
the static keyword. When we introduce some of the Java libraries (for
example the Math package) I’ll explain why you might use it.
The major issue that some of you have run into with the static methods is
that you get errors when you try to access any method that is non-static!
CS 5JA Introduction to Java
Static?
For instance, the main method is always static. When your program starts,
NO objects are instantiated, but we still need to start somewhere! But you
can’t do anything complicated until you instantiate an object. Instance
variables do not exist, because there is no instance of anything yet!
On the other hand, the other way around works fine: regular, non-static
methods can access static instance variables. Static variables exist even if
the object isn’t created yet... But this can be confusing... see code...
(code example: http://cs.ucsb.edu/~cs5ja/examples/StaticExample.java)
So, use your main method to instantiate objects, and don’t try to access
instance variables until you actually have created an object to work with!
CS 5JA Introduction to Java
More about methods...
You can have more than one method with the exact same name. But they
might have different signatures.
For instance, in the Account class we have a method called setType. The
signature for setType is:
public void setType(String accountType)
But we could also add another method also called setType but that has a
different signature:
public void setType(String accountType, long timestamp)
In this version you pass in a timestamp because you decide that you want
to record when the account type was edited.
CS 5JA Introduction to Java
More about methods...
For all practical purposes, according to the compiler these are totally
different methods! The only thing that is the same is the name, and that is
only to help you organize your code. Practically, the methods should be
very similar, otherwise your method names won’t make very much sense.
Say you also wanted to keep track of the type of person using the account
(say we want to know if the user is a student versus a professional, etc).
The compiler would get confused however if you made these two methods:
public void setType(String accountType)
public void setType(String typeOfPerson)
Even though the variables have different names, they have the same
signature, so the compiler spits out an error.
CS 5JA Introduction to Java
More about methods...
A method’s signature has a few different parts.
1) accessibility: public, private, protected
2) return data type: the object/primitive data it returns (Account, int, String,
Scanner, etc)
3) method name
4) the data types that are passed in (ie the paramaters or arguments)
The combination of 3 and 4 must be unique.
CS 5JA Introduction to Java
More about methods...
What is the difference between public and private?
a public method means that the method can be accessed and invoked
from outside of the object. For example, our AtmMachine invoked the
checkBalance method inside the checkingAccount object.
This would not have worked if the method was only privately accessible
method.
A method is private if you want to insure that no one else can access the
method except the object itself.
CS 5JA Introduction to Java
More about methods...
For example, we might want to make sure that only certain methods are
available to the outside world. We might do this for security reasons, or to
make things simpler for other classes.
public boolean isUserReallyACriminal(String name, long socialSecurity)
{
boolean isCriminal = checkSecretData(socialSecurity);
if (isCriminal)
{
alertPolice()
return true;
}
return false;
}
private boolean checkSecretData(long socialSecurity)
{ //do secret stuff... }
CS 5JA Introduction to Java
More about methods...
Thinking about what methods (and instance variables) that you want to make
publicly available is thinking about how you want other classes to “interface” with
you class.
There are thousands of classes in the java library. We might want to use their
functionality to make something happen, but we don’t really care how it happens.
For example, in the Scanner class we use the publicly available method “nextInt()”
which reads an int from the command line for us. But we don’t care how it does it.
Obviously there is all sorts of complicated code that talks to the operating system,
etc. But it is hidden from us. The “interface” is the set of publicly available methods
that let us focus on the useful things it does, rather than the complicated ways it
does it.
A real-world example is a car. You interface with the car by putting the key in the
ignition. You don’t care at all about how it ignites a spark, which starts the engine,
which fires up the pistons, etc. If you had to think about that every time you started
a car, it might take a while for you to get anywhere. Those complicated methods
are private. They are off-limits except to experts– in this case auto-mechanics.
CS 5JA Introduction to Java
More about methods...
Let’s go back to methods again:
I said that a signature is unique based on its name and the data types of its
arguments. Would the compiler accept these?
public void method1()
public String method1()
private String method1()
public String method1()
private int method1(boolean fact)
private int method1(boolean aDifferentFact)
private int method1(boolean fact)
private int method1(boolean fact, boolean aDifferentFact)
CS 5JA Introduction to Java
Multiple Constructors
Now the same thing applies to the constructor, except that the signature
doesn’t include a return type.
public Account(String accountType, int initialBalance)
{
type = accountType;
balance = initialBalance;
}
public Account(String accountType)
{
type = accountType;
balance = 0;
}
CS 5JA Introduction to Java
Multiple Constructors
But this doesn’t work...
public Account(int initialBalance)
{
balance = initialBalance;
}
public Account(int initialBonusPoints)
{
bonusPoints = boinusPoints
}
CS 5JA Introduction to Java
Scope
Every variable has a certain lifetime. When that lifetime is over, it gets
thrown into the trash. In all but a few strange cases, Java is smart enough
to figure out when data is no longer needed. It handles it own garbage
collection.
However, a programmer can make some errors if they don’t realize that a
variable isn’t around anymore.
Also, programmers can make errors if they try to use a variable that isn’t
initialized yet.
The range of a variable’s lifetime is called its scope. And there are a few
things to be aware of. Usually the compiler will tell you if there is a
problem, but in certain cases it can’t.
CS 5JA Introduction to Java
Scope
The scope of an instance variable is anywhere in the entire object. Unless it is
shadowed by a local variable.
int x = 5;
public void method1()
{
int y = 10;
System.out.println(“ x = “ + x);
}
public void method2()
{
int x = 10;
System.out.println(“ x = “ + x);
}
The x in method2 is a completely different variable– it just happens to have the
same name. method2() does not overwrite the instance variable. At the end of
method2, our local variable (with the name x) is no longer alive, and gets thrown in
the garbage. Any references to x in other methods will again refer to the instance
variable. The local variable x inside of method2 is said to shadow the instance
variable.
CS 5JA Introduction to Java
Scope
The scope of a local variable is from the point it was defined until the end
of that code block.
public void method()
{
int x = 5;
//lots of code...
}
Since x was created and initialized at the first line of the method, anything
that follows can use or change x.
CS 5JA Introduction to Java
Scope
What will happen here?
public void method()
{
int x;
if (x == 5)
{
System.out.println(“x = 5!!!”);
}
}
CS 5JA Introduction to Java
Scope
What will happen here?
public void method()
{
int x;
if (x == 5)
{
System.out.println(“x = 5!!!”);
}
}
A variable needs to defined and initialized before it is used. In this case,
the variable is in scope, but since nothing has been assigned to it, the
compiler prints an error.
CS 5JA Introduction to Java
Scope
What will happen here?
public void method()
{
for (int i = 1; i <= 5; i++)
{
int x = 5;
System.out.println(“looping through ” + i + “ of “ + x);
}
System.out.println(“We have successfully looped through “ + x + loops”);
}
CS 5JA Introduction to Java
Scope
What will happen here?
public void method()
{
for (int i = 1; i <= 5; i++)
{
int x = 5;
System.out.println(“looping through ” + i + “ of “ + x);
}
System.out.println(“We have successfully looped through “ + x + loops”);
}
x was defined within a code block. Thus, it dies at the end of the code
block. In this case the block is the for loop. Thus outside the for loop we no
longer can refer to x. In fact, this code is creating and destroying x in every
iteration of the loop.
CS 5JA Introduction to Java
Scope
What will happen here?
int x = 10; //instance variable
public void method()
{
for (int i = 1; i <= 5; i++)
{
int x = 5;
System.out.println(“looping through ” + i + “ of “ + x);
}
System.out.println(“We have successfully looped through “ + x + loops”);
}
CS 5JA Introduction to Java
Scope
What will happen here?
int x = 10; //instance variable
public void method()
{
int x = 5;
for (int i = 1; i <= 5; i++)
{
System.out.println(“looping through ” + i + “ of “ + x);
}
System.out.println(“We have successfully looped through “ + x + loops”);
}
CS 5JA Introduction to Java
Graphics
http://java.sun.com/javase/6/docs/api/java/awt/Graphics.html
One of the powerful things about Java is that there is a large library of
code that already exists. Not only can you use it, but you can extend the
library with your own custom code. We’ll talk more about his in detail in a
later class, but I just want to give you enough to use the built in userinterface widgets (called “Swing”) so that you can make some simple 2D
graphics.
The basic “widget” in Java is called a “JFrame” (J for java...). A frame is the
square object that contains an application. It usually has a title bar, a
button for minimizing and closing the application, and a panel that contains
the content of the application. This panel is called a JPanel (J for java...).
You can create your own JPanel and do anything you want to it. For our
next homework assignment we’re going to learn how to make digital art.
CS 5JA Introduction to Java
Graphics
The JPanel contains lots of built-in methods to handle all sorts of things,
like recognizing mouse focus, knowing how to minimize itself, knowing
when to be behind another application, etc. So we can utilize all of this
functionality, but customize it for our purposes.
Here’s how we do it:
public class MyArtwork extends JPanel
The JPanel object has a built-in method called paintComponent which
describes how to draw itself. By default it just draws a big gray square.
You can override this method and tell your JPanel to draw itself in a more
interesting way.
CS 5JA Introduction to Java
Graphics
//overriding!
public void paintComponent(Graphics artist)
{
//dip paintbrush into new color
artist.setColor(Color.BLACK);
//paint a rectangle
artist.fillRect(30, 30, 100, 100);
}
Each JPanel has a built-in palette and a built-in artist. The artist is prized
for his graphics abilities, so he is of data type “Graphics”. Here we name
him “artist”. In this method, we are telling the artist inside JPanel to paint
the screen. In the first line we are telling artist to change colors. In the
second line we are telling him to draw a rectangle.
CS 5JA Introduction to Java
Graphics
You can set the color using built-in colors, or by defining your own color
using its RGB values.
Let’s make a new color and tell the artist to use it:
Color newColor = new Color( 255,
//Red
artist.setColor(newColor);
0,
Green
0 );
Blue
The range of the canvas is defined by pixel values. You can think of a
graph, except the origin (0, 0) is in the top-left corner, and the y value is
reversed. The y-value increases as you go down. The x-value increases as
you go toward the right.
Code example...
CS 5JA Introduction to Java
Why do variables change names?
You can see that eventually the word “checking” is assigned to the instance
variable type. But to get there we make 3 other variables! (myAccount,
accountType, and typeOfAccount)
String type;
public Account(String accountType)
{
setType(accountType);
}
public void setType(String typeOfAccount)
{
type = typeOfAccount;
}
And we called the constructor from AtmMachine like this:
String myAccount = “checking”;
new Account(myAccount);