Ch2-IntroductionToJava

advertisement
Problem Solving with Data
Structures using Java:
A Multimedia Approach
Chapter 2: Introduction to
Java
Chapter Objectives




Explain why Java is relevant to modeling and
simulation.
Give the basic syntax details for variables,
arrays, iteration, and conditionals.
Explain how to create a class and a
subclass.
Give the user a brief introduction to the
manipulation of pictures, sounds, and music.
Things to do to get started





Download and install JDK (Java
Development Kit)
Download and install DrJava
Download JMusic
Download the Java source files for class
Then, tell Java where to find the JMusic
and Java source files.
Parts of DrJava
List of
class
files that
you have
open
Text of
your
class file
(.java)
Where you
interact
with Java
Java is object-oriented


95% of everything in Java is an object.
In object-oriented programming, you
care about more than just specifying the
process.
• You care about who (or what) does the
•
process,
And how the overall process emerges from
the interaction of different objects.
Object-oriented programming is
about modeling and simulation


The whole idea of object-oriented
programming is to create a model of the part of
the world (real or imaginary).
Creates constraints:
•
•
The real world doesn’t have one set of rules/steps.
• You don’t write one big program.
In the real world, no one knows everything, no one
can do everything.
• Each object has it’s own things it knows and things it
can do.
Example: A movie theater

Different jobs in the theater: ticket-seller,
ticket-taker, drink-seller, theater-cleaner.
• Different skills for each.

Classes track what objects can do
(methods) and know (fields).
Associations and Inheritance

All movie showings havea (association) movie
(with name and length),
and a time.
•
•

Private showings have
contact information, too
PublicShowing and
PrivateShowing are
subclasses (children) of
MovieShowing.
This diagram represents
that in UML.
Responsibility-Driven Design

Each object is responsible for knowing
things and doing things appropriate to its
type.
• The title of the movie belongs with the movie,
not with the movie showing.

You want to distribute responsibility
across your objects to decrease
complexity in programming.
Variables in Java know their
types



Variables in Java know that kinds of things
(values) they can hold.
Objects in Java are organized into classes.
•
•
A class specifies what all the objects of that class
know and can do.
All pictures can show themselves, even though each
picture is different.
Variables in Java are specific to particular
classes.
•
We declare a variable to only hold objects of particular
classes.
Declaring and setting variables
with types
Int (integers) can only
hold numbers without
decimal points
Variables values can
be changed, but not
re-declared.
Other types: char, boolean,
float, double
> char firstLetter = ’a’;
> System.out.println(firstLetter);
’a’
> boolean flag = true;
> System.out.println(flag)
True
> float f = 13.2f
>f
13.2
> double d;
> d = 13.231;
>d
13.231
> d+f
26.43099980926514
> a=f
Error: Bad types in assignment
> a=(int) f
13
Strings
What do strings know?
Check the API!

Check the API at java.sun.com
Object and Primitive variables


Primitive variables (like the int a) reference memory associated
with that name.
Object variables (like the String s) refer to an object reference,
that points to the actual object.
•
•
Object variables can reference an object, or any child of the object.
The actual objects could have different fields, and thus, different
memory sizes.
null, a special value



null is an object variable value that
means “doesn’t refer to any object.”
It’s not zero, it’s not true, it’s not false.
It’s just null.
Conditionals
IF ( EXPRESSION)
STATEMENT
IF (EXPRESSION)
STATEMENT
Else
STATEMENT
Can use curly braces to have
more than statement after IF.
Arrays

Declare an array with type[ ], like
Picture[ ] to create an array of pictures.
myArray.length here will be 4.
Iteration with FOR
FOR (type variable: array)
STATEMENT
Iteration with FOR (part 2)
FOR (initial-expression;
continuing-condition;
iteration-expression)
STATEMENT
Incrementing variables is so
common, there’s a shorthand.
Iteration with WHILE

WHILE (expression)
STATEMENT
Strings are objects, not arrays
of characters

Arrays of
characters:

Strings
Using Java to Model the World

Object-oriented programming is explicitly
about creating a simulation of the world.
• The classes in the program are meant to
•
•
simulate kinds of things in the world.
The relationships between classes is meant to
simulate relationships in the world.
The knowledge and behavior of instances are
meant to simulate what real objects “know”
and “do.”
Getting the level right


How much do you model?
Answer: Depends on what you care about.
Imagine a simulation of a vending machine.
• Want to know how much force the can withstands
•
when it hits the bottom? Better model height of
the racks, weight of the cans, and gravity.
Want to know how purchases are processed?
Then you want to model selections and sales
transactions (and you can ignore gravity).
A Sample Model

Imagine that we want to model students in
terms of how they register for classes
(as opposed to what they eat, how they don’t sleep, and how
they gain the Freshman-15).
• We care about students having names and
identification numbers.
• (We don’t care about nutrition, metabolism, and
exercise, then.)
• But we don’t want our Student class to have a
name and an id, because Students don’t have
names. People do
A Student Model

Person is the general, superclass.

Student is a subclass of Person.
• A Person has a name.
• A Student has a student identification number
(“id”).

Because Student inherits from Person, all
methods and fields (or instance variables
from Person exist in every instance of
Student.
• That is, Students have both names and ids.
Starting a Definition of Person


Any class can make instances
from a public class.
A public field (the String name)
can be accessed directly from
any instance of Person.
•
•
A private field can only be
accessed by the class’s methods.
All fields are inherited in
subclasses, even private ones,
though only the superclass’s
methods can manipulate those
fields
Using our new Person class


object.field references the
field instance variable in
the object.
object.method() executes
the method in the object.

We create instances
with new and the
classname().
The variable fred has
type Person, so it can
hold an instance of
Person.
The name initially has
no value – it’s null.
Public Fields can be Changed
Anywhere


Should we be able
to tell the instance
in Fred that its
name is now
“Mabel”?
Should names be
changeable
anywhere?
Definition #2: Making names
private
setName() is void,
because it doesn’t
return anything.
getName() returns a
String.

Now name is private. It can only be
changed with setName() and read with
getName()
Trying out Definition #2

Should People have names as soon as
they are created?
Definition #3: Using
constructors

Constructors are
called via
Person(), to
initialize an
object.
Accessing Constructors
Discourse Rules for Java






Not syntax rules. It’s just “the way we talk” in Java.
•
The sheriff in a Western says, “Howdy!” not “Wassup?”
Class names start with a capital letter.
•
Additional words in the name are capitalized.
Class names are never plural.
Class names are nouns, not verbs.
Methods are named for what the object knows
how to do.
Field accessors and modifiers are named
setField() and getField().
Making objects print nicely


When we print an object, the toString()
method is called.
We can make it print something nicer
than an internal object reference
number.
Adding toString() to Person

Now, Person instances can
print themselves by name:
Strings can be
concatenated
(combined) with +
Designing the Student class

By default, all classes inherit
from (extend) the class
Object.
•


That’s where toString() is that
returns the funny number.
We’ll make Student a
subclass of Person.
This is the UML diagram
showing these relationships.
Student Definition#1: A Student
has an ID
This goes in a file
named Student.java
Using our Student definition
But there’s a problem

Students can’t be created with names?
 No-argument default constructor will
always work.
 If we want to access superclass’s
constructor, have to set up constructors
that call super().
Student Definition #2
If you’re going to call
the superclass
constructor, call
super() as the first
statement in the
constructor.
Trying out Student definition #2
Creating a test method for
Person

This method is always called public
static void main(String[] args)
Exploring inheritance

A greet() method for Person
Overriding greet() in Student

Can’t just say this.name because name
is private.
Variables, Types and Classes

A variable of type superclass can hold
any subclass, but not vice-versa.
Accessing subclass parts
requires casting
Summarizing the terms so-far




Just about everything in Java is an object
Objects know specific things and can do specific things
•
•
Things they know are stored in variables (data)
Things they can do are grouped into methods
•
Think of methods as “functions known only to instances of that
class.”
Objects are instances of a given class in Java.
•
All the instances know the same things and can do the
same things.
Variables are specific to a given class, and can only refer
to objects of that type.
Manipulating Pictures in Java

The class Picture has a constructor that
takes a filename and returns a picture.
• A picture can show()

FileChooser.pickAFile() returns a filename
Explaining what’s going on
> Picture p;
> p = new
Picture("D:/cs1316/
MediaSources/Swa
n.jpg");
> p.show();
• Every line ends with a
semi-colon in Java.
•(DrJava doesn’t always
require it.)
• Picture is the name of a
class in Java.
• p is the variable that we’re
declaring
In Java programs, You can only use declared variables!
And you can only declare them once per scope!
Explaining what’s going on
> Picture p;
> p = new
Picture("D:/cs1316/
MediaSources/Swa
n.jpg");
> p.show();
• new Picture() creates a
new picture.
• The pathname
provided as an argument
tells it which picture.
• You can always use “/”
and it’ll always work (on
any platform)
• p now refers to the new
object (instance of class
Picture)
Explaining what’s going on
> Picture p;
> p = new
Picture("D:/cs1316/
MediaSources/Swa
n.jpg");
> p.show();
• Instances of the class
Picture (objects created
from the class Picture) know
how to show themselves.
• We access what the object
knows and can do with the
dot operator.
• p.show() says “Object that
p refers to, would you
please execute your show()
method?”
Semicolons or not in
DrJava Interactions Pane
No semi-colon says “Evaluate this, and show
me the result.”
 Semi-colon says “Treat this like a line of code,
just as if it were in the Code Pane.”
>p
Picture, filename
D:/cs1316/MediaSources/Swan.jpg height 360
width 480
> p;
>

Pictures are made up of Pixels

Pictures are made up of “picture
elements” called Pixels.
• Pixel[] declares an array of Pixel objects.

Each Pixel has a red, green, and blue
channel, which combine to show us a
color for that Pixel.
Increasing red from DrJava
Interaction pane
Defining a method in Picture to
doubleRed()
Trying out our doubleRed()
method
Testing doubleRed() on Big Ben
Adding the ability to flip()
pictures (1 of 2)
/**
* Method to flip a picture
*/
public Picture flip () {
// declare some local variables
Pixel currPixel = null;
Pixel targetPixel = null;
Picture target =
new Picture(this.getWidth (),this.getHeight ());
/* loop through the picture with the source x starting at 0
* and the target x starting at the width minus one */
for (int srcX = 0, trgX = getWidth ()-1;
srcX < getWidth ();
srcX++, trgX --) {
for (int srcY = 0, trgY = 0;
srcY < getHeight ();
srcY++, trgY ++) {
// get the current pixel
currPixel = this.getPixel(srcX ,srcY );
targetPixel = target.getPixel(trgX ,trgY );
// copy the color of currPixel into target
targetPixel.setColor(currPixel.getColor ());
}
}
return target;
}
Finishing flip()
Testing flip()
Testing flip()
Exploring sounds in Java
Explaining what’s going on
> Sound s = new
Sound(FileChooser.pickAFile());
> s.play();
 We can create an object as we declare the
variable.
 FileChooser is an object that knows how to
pickAFile() which puts up a file picker and
returns a string.
 Instances of the class Sound know how to
play, thus s.play()
What if we get it wrong?
An example with Music
> import jm.util.*;
> import jm.music.data.*;
> Note n1;
> n1 = new Note(60,0.5);
> // Create an eighth note
at C octave 4
• JMusic pieces
need to be
imported first to
use them.
Exploring Music in Java
> import jm.util.*;
> import jm.music.data.*;
> Note n1;
> n1 = new Note(60,0.5);
> // Create an eighth note
at C octave 4
• Declare a Note
variable.
An example with Music
> import jm.util.*;
> import jm.music.data.*;
> Note n1;
> n1 = new Note(60,0.5);
> // Create an eighth note
at C octave 4
Starting a line with // creates a
comment—ignored by Java
• Note instances
have nothing to do
with filenames.
• To create a note,
you need to know
which note, and a
duration
MIDI notes
Making more notes
> Note n2=new Note(64,0.5);
> View.notate(n1);
Error: No 'notate' method in
'jm.util.View' with arguments:
(jm.music.data.Note)
> Phrase phr = new Phrase();
> phr.addNote(n1);
> phr.addNote(n2);
> View.notate(phr);
-- Constructing MIDI file
from'Untitled Score'...
Playing with JavaSound ...
Completed MIDI playback -------
What’s going on here?
> Note n2=new Note(64,0.5);
> View.notate(n1);
Error: No 'notate' method in
'jm.util.View' with arguments:
(jm.music.data.Note)
• We’ll make another Note (at E4,
another eighth note)
• There is an object named View
that knows how to notate parts of
music, but not an individual note.
What’s going on here?
> Phrase phr = new Phrase();
> phr.addNote(n1);
> phr.addNote(n2);
> View.notate(phr);
-- Constructing MIDI file
from'Untitled Score'... Playing
with JavaSound ... Completed
MIDI playback --------
• We’ll create a new Phrase
instance and make a variable phr to
refer to it. (phr has to be declared
to be a Phrase.)
• Phrase instances know how to
addNote notes to them. These are
methods that take an argument—a
Note instance.
• The View object does know how
to notate an input Phrase instance.
It generates this cool window where
you see the notes and can play
them (or save them as MIDI.)
Playing a different Phrase
> Phrase nuphr = new
Phrase(0.0,JMC.FLU
TE);
> nuphr.addNote(n2);
> nuphr.addNote(n1);
> View.notate(nuphr);
• We can specify when a phrase starts and with what
instrument.
• We can add notes (even the same notes!) in different
orders
Modeling Music

The JMusic package is really modeling
music.
• Notes have tones and durations.
• Musical Phrases are collections of notes.
• We can play (and View) a musical phrase.
• A phrase doesn’t have to start when other phrases
do, and a phrase can have its own instrument.
Objects know things and can do
things
What
instances of
this class
know
What
instances of
this class can
do
Note
A musical pitch
and a duration
<Nothing we’ve
seen yet>
Phrase
The notes in the
phrase
addNote(aNote)
The Organization of
JMusic Objects
Score: timeSignature, tempo, &
Part: Instrument &
Part: Instrument &
Phrase: startingTime &
Note
(pitch,duration)
Note
(pitch,duration)
Note
(pitch,duration)
Phrase: startingTime &
Note
(pitch,duration)
Note
(pitch,duration)
Download