Title: Problem Solving with Data Structures using Java: A Multimedia Approach
1Problem Solving with Data Structures using Java
A Multimedia Approach
- Chapter 2 Introduction to Java
2Chapter 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.
3Things 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.
4Parts of DrJava
List of class files that you have open
Text of your class file (.java)
Where you interact with Java
5Java 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.
6Object-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 doesnt have one set of
rules/steps. - You dont write one big program.
- In the real world, no one knows everything, no
one can do everything. - Each object has its own things it knows and
things it can do.
7Example 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).
8Associations and Inheritance
- All movie showings have-a (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.
9Responsibility-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.
10Variables 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.
11Declaring and setting variables with types
Int (integers) can only hold numbers without
decimal points
Variables values can be changed, but not
re-declared.
12Other types char, boolean, float, double
- gt char firstLetter a
- gt System.out.println(firstLetter)
- a
- gt boolean flag true
- gt System.out.println(flag)
- True
- gt float f 13.2f
- gt f
- 13.2
- gt double d
- gt d 13.231
- gt d
- 13.231
- gt df
- 26.43099980926514
- gt af
- Error Bad types in assignment
- gt a(int) f
- 13
13Strings
14What do strings know?Check the API!
- Check the API at java.sun.com
15Object 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.
16null, a special value
- null is an object variable value that means
doesnt refer to any object. - Its not zero, its not true, its not false.
- Its just null.
17Conditionals
- IF ( EXPRESSION)
- STATEMENT
- IF (EXPRESSION)
- STATEMENT
- Else
- STATEMENT
Can use curly braces to have more than statement
after IF.
18Arrays
- Declare an array with type , like Picture to
create an array of pictures.
myArray.length here will be 4.
19Iteration with FOR
- FOR (type variable array)
- STATEMENT
20Iteration with FOR (part 2)
- FOR (initial-expression
continuing-condition
iteration-expression) - STATEMENT
Incrementing variables is so common, theres a
shorthand.
21Iteration with WHILE
- WHILE (expression) STATEMENT
22Strings are objects, not arrays of characters
- Arrays of characters
- Strings
23Using 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.
24Getting 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).
25A 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 dont sleep, and how they
gain the Freshman-15). - We care about students having names and
identification numbers. - (We dont care about nutrition, metabolism, and
exercise, then.) - But we dont want our Student class to have a
name and an id, because Students dont have
names. People do
26A Student Model
- Person is the general, superclass.
- A Person has a name.
- Student is a subclass of Person.
- 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.
27Starting 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
classs methods. - All fields are inherited in subclasses, even
private ones, though only the superclasss
methods can manipulate those fields
28Using our new Person class
- 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 its null.
object.field references the field instance
variable in the object. object.method() executes
the method in the object.
29Public 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?
30Definition 2 Making names private
setName() is void, because it doesnt return
anything.getName() returns a String.
- Now name is private. It can only be changed with
setName() and read with getName()
31Trying out Definition 2
- Should People have names as soon as they are
created?
32Definition 3 Using constructors
- Constructors are called via Person(), to
initialize an object.
33Accessing Constructors
34Discourse Rules for Java
- Not syntax rules. Its 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().
35Making 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.
36Adding toString() to Person
Strings can be concatenated (combined) with
- Now, Person instances can print themselves by
name
37Designing the Student class
- By default, all classes inherit from (extend) the
class Object. - Thats where toString() is that returns the funny
number. - Well make Student a subclass of Person.
- This is the UML diagram showing these
relationships.
38Student Definition1 A Student has an ID
This goes in a file named Student.java
39Using our Student definition
40But theres a problem
- Students cant be created with names?
- No-argument default constructor will always work.
- If we want to access superclasss constructor,
have to set up constructors that call super().
41Student Definition 2
If youre going to call the superclass
constructor, call super() as the first statement
in the constructor.
42Trying out Student definition 2
43Creating a test method for Person
- This method is always called public static void
main(String args)
44Exploring inheritance
- A greet() method for Person
45Overriding greet() in Student
- Cant just say this.name because name is private.
46Variables, Types and Classes
- A variable of type superclass can hold any
subclass, but not vice-versa.
47Accessing subclass parts requires casting
48Summarizing 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.
49Manipulating 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
50(No Transcript)
51Explaining whats going on
- Every line ends with a semi-colon in Java.
- (DrJava doesnt always require it.)
- Picture is the name of a class in Java.
- p is the variable that were declaring
- gt Picture p
- gt p new Picture("D/cs1316/MediaSources/Swan.jpg
") - gt p.show()
In Java programs, You can only use declared
variables! And you can only declare them once per
scope!
52Explaining whats going on
- new Picture() creates a new picture.
- The pathname provided as an argument tells it
which picture. - You can always use / and itll always work (on
any platform) - p now refers to the new object (instance of
class Picture)
- gt Picture p
- gt p new Picture("D/cs1316/MediaSources/Swan.jpg
") - gt p.show()
53Explaining whats going on
- 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?
- gt Picture p
- gt p new Picture("D/cs1316/MediaSources/Swan.jpg
") - gt p.show()
54Semicolons 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. - gt p
- Picture, filename D/cs1316/MediaSources/Swan.jpg
height 360 width 480 - gt p
- gt
55Pictures 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.
56Increasing red from DrJava Interaction pane
57Defining a method in Picture to doubleRed()
58Trying out our doubleRed() method
59Testing doubleRed() on Big Ben
60Adding 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 ())
61Finishing flip()
- / 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 lt getWidth ()
- srcX, trgX --)
- for (int srcY 0, trgY 0
- srcY lt 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
62Testing flip()
63Testing flip()
64Exploring sounds in Java
65Explaining whats going on
- gt Sound s new Sound(FileChooser.pickAFile())
- gt 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()
66What if we get it wrong?
67An example with Music
- gt import jm.util.
- gt import jm.music.data.
- gt Note n1
- gt n1 new Note(60,0.5)
- gt // Create an eighth note at C octave 4
- JMusic pieces need to be imported first to use
them.
68Exploring Music in Java
- gt import jm.util.
- gt import jm.music.data.
- gt Note n1
- gt n1 new Note(60,0.5)
- gt // Create an eighth note at C octave 4
69An example with Music
- gt import jm.util.
- gt import jm.music.data.
- gt Note n1
- gt n1 new Note(60,0.5)
- gt // Create an eighth note at C octave 4
- Note instances have nothing to do with
filenames. - To create a note, you need to know which note,
and a duration
Starting a line with // creates a commentignored
by Java
70MIDI notes
71Making more notes
- gt Note n2new Note(64,0.5)
- gt View.notate(n1)
- Error No 'notate' method in 'jm.util.View' with
arguments (jm.music.data.Note) - gt Phrase phr new Phrase()
- gt phr.addNote(n1)
- gt phr.addNote(n2)
- gt View.notate(phr)
- -- Constructing MIDI file from'Untitled Score'...
Playing with JavaSound ... Completed MIDI
playback --------
72Whats going on here?
gt Note n2new Note(64,0.5) gt View.notate(n1) Err
or No 'notate' method in 'jm.util.View' with
arguments (jm.music.data.Note)
- Well 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.
73Whats going on here?
gt Phrase phr new Phrase() gt phr.addNote(n1) gt
phr.addNote(n2) gt View.notate(phr) --
Constructing MIDI file from'Untitled Score'...
Playing with JavaSound ... Completed MIDI
playback --------
- Well 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 argumenta
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.)
74Playing a different Phrase
- gt Phrase nuphr new Phrase(0.0,JMC.FLUTE)
- gt nuphr.addNote(n2)
- gt nuphr.addNote(n1)
- gt 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
75Modeling 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 doesnt have to start when other phrases
do, and a phrase can have its own instrument.
76Objects 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 ltNothing weve seen yetgt
Phrase The notes in the phrase addNote(aNote)
77The Organization of JMusic Objects
Score timeSignature, tempo,
Part Instrument
Part Instrument
Phrase startingTime
Phrase startingTime
Note (pitch,duration)
Note (pitch,duration)
Note (pitch,duration)
Note (pitch,duration)
Note (pitch,duration)