Problem Solving with Data Structures using Java: A Multimedia Approach Chapter 2: Introduction to Java.

Slides:



Advertisements
Similar presentations
AP Computer Science Anthony Keen. Computer 101 What happens when you turn a computer on? –BIOS tries to start a system loader –A system loader tries to.
Advertisements

Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
TOPIC 12 CREATING CLASSES PART 1 1 Notes adapted from Introduction to Computing and Programming with Java: A Multimedia Approach by M. Guzdial and B. Ericson,
Animation Mrs. C. Furman. Animation  We can animate our crab by switching the image between two pictures.  crab.png and crab2.png.
Week 10: Objects and Classes 1.  There are two classifications of types in Java  Primitive types:  int  double  boolean  char  Object types: 
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Road Map Introduction to object oriented programming. Classes
Arrays. A problem with simple variables One variable holds one value –The value may change over time, but at any given time, a variable holds a single.
COMP 14: Primitive Data and Objects May 24, 2000 Nick Vallidis.
Programming Concepts MIT - AITI. Variables l A variable is a name associated with a piece of data l Variables allow you to store and manipulate data in.
Games and Simulations O-O Programming in Java The Walker School
Chapter 6: Graphical User Interface (GUI) and Object-Oriented Design (OOD) J ava P rogramming: Program Design Including Data Structures Program Design.
Week 10 - Monday.  What did we talk about last time?  Method overloading  Lab 9.
3.1 Documentation & Java Language Elements Purpose of documentation Assist the programmer with developing the program Assist other programers who.
Introduction to Programming Writing Java Beginning Java Programs.
CPSC1301 Computer Science 1 Chapter 11 Creating Classes part 1.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
CreatingClasses-part11 Creating Classes part 1 Barb Ericson Georgia Institute of Technology Dec 2009.
An Introduction to Java Chapter 11 Object-Oriented Application Development: Part I.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Chapter 8 Objects and Classes.
Introduction to Java CS1316: Representing Structure and Behavior.
Georgia Institute of Technology Creating Classes part 1 Barb Ericson Georgia Institute of Technology Oct 2005.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Sun Certified Java Programmer, ©2004 Gary Lance, Chapter 1, page 1 Sun Certified Java 1.4 Programmer Chapter 1 Notes Gary Lance
CSC 142 Computer Science II Zhen Jiang West Chester University
CIT 590 Intro to Programming First lecture on Java.
Checking Equality of Reference Variables. Arrays and objects are both “reference” types n They are allocated a chunk of memory in the address space n.
CSC1401 Classes - 1. Learning Goals Computing concepts Identifying objects and classes Declaring a class Declaring fields Default field values.
Java development environment and Review of Java. Eclipse TM Intergrated Development Environment (IDE) Running Eclipse: Warning: Never check the “Use this.
1 Programming Week 2 2 Inheritance Basic Java Language Section.
CSC1401 Classes - 2. Learning Goals Computing concepts Adding a method To show the pictures in the slide show Creating accessors and modifiers That protect.
Introduction to Programming Writing Java Beginning Java Programs.
Chapter 6 Introduction to Defining Classes. Objectives: Design and implement a simple class from user requirements. Organize a program in terms of a view.
BEGINNING PROGRAMMING.  Literally – giving instructions to a computer so that it does what you want  Practically – using a programming language (such.
Chapter 4&5 Defining Classes Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Java Programming: From Problem Analysis to Program Design, 3e Chapter 6 Graphical User Interface (GUI) and Object-Oriented Design (OOD)
Java Programming: From Problem Analysis to Program Design, Second Edition1 Lecture 5 Objectives  Learn about basic GUI components.  Explore how the GUI.
CreatingClasses-SlideShow-part31 Creating Classes part 3 Barb Ericson Georgia Institute of Technology Dec 2009.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All rights reserved Objects and Classes.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Inheritance and Class Hierarchies Chapter 3. Chapter 3: Inheritance and Class Hierarchies2 Chapter Objectives To understand inheritance and how it facilitates.
TeachJava! 2003 Corky Cartwright Dung Nguyen Stephen Wong Charlie Reis, James Hsia, Peter Centgraf.
Arrays-. An array is a way to hold more than one value at a time. It's like a list of items.
Week 10 - Wednesday.  What did we talk about last time?  Method example  Roulette simulation  Types in Java.
SourceAnatomy1 Java Source Anatomy Barb Ericson Georgia Institute of Technology July 2008.
1.1: Objects and Classes msklug.weebly.com. Agenda: Attendance Let’s get started What is Java? Work Time.
M1G Introduction to Programming 2 2. Creating Classes: Game and Player.
OOP Basics Classes & Methods (c) IDMS/SQL News
Chapter 6 Graphical User Interface (GUI) and Object-Oriented Design (OOD)
CSCI 51 Introduction to Programming Dr. Joshua Stough February 24, 2009.
Georgia Institute of Technology More on Creating Classes Barb Ericson Georgia Institute of Technology June 2006.
CS100Lecture 61 Announcements Homework P1 due on Thursday Homework P2 handed out.
Eastside Robotics Alliance / Newport Robotics Group 1 T/Th, 6:30 – 8:30 PM Big Picture School Day 3 · 10/9/2014.
CS1316: Representing Structure and Behavior
CS1316: Representing Structure and Behavior
Yanal Alahmad Java Workshop Yanal Alahmad
Java Primer 1: Types, Classes and Operators
CS1316: Representing Structure and Behavior
Java Programming: From Problem Analysis to Program Design,
CS1316: Representing Structure and Behavior
CS1316: Representing Structure and Behavior
Barb Ericson Georgia Institute of Technology Oct 2005
Recap Week 2 and 3.
Barb Ericson Georgia Institute of Technology June 2005
More on Creating Classes
Barb Ericson Georgia Institute of Technology Oct 2005
CS1316: Representing Structure and Behavior
Review for Midterm 3.
Presentation transcript:

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 Text of your class file (.java) Where you interact with Java List of class files that you have open

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 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.

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 = ; > d > d+f > 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. 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.

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 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. object.field references the field instance variable in the object. object.method() executes the method in the object.

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 Now name is private. It can only be changed with setName() and read with getName() setName() is void, because it doesn’t return anything. getName() returns a String.

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()

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 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 comment—ignored by Java

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 Phrase The notes in the phrase addNote(aNote)

Part: Instrument & Phrase: startingTime & The Organization of JMusic Objects Phrase: startingTime & Note (pitch,duration) Part: Instrument & Score: timeSignature, tempo, &