1 / 77

Problem Solving with Data Structures using Java: A Multimedia Approach

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.

tab
Télécharger la présentation

Problem Solving with Data Structures using Java: A Multimedia Approach

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


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

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

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

  4. Parts of DrJava List of class files that you have open Text of your class file (.java) Where you interact with Java

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

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

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

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

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

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

  11. Declaring and setting variables with types Int (integers) can only hold numbers without decimal points Variables values can be changed, but not re-declared.

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

  13. Strings

  14. What do strings know?Check the API! • Check the API at java.sun.com

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

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

  17. Conditionals IF ( EXPRESSION) STATEMENT IF (EXPRESSION) STATEMENT Else STATEMENT Can use curly braces to have more than statement after IF.

  18. Arrays • Declare an array with type[ ], like Picture[ ] to create an array of pictures. myArray.length here will be 4.

  19. Iteration with FOR FOR (type variable: array) STATEMENT

  20. Iteration with FOR (part 2) FOR (initial-expression; continuing-condition; iteration-expression) STATEMENT Incrementing variables is so common, there’s a shorthand.

  21. Iteration with WHILE • WHILE (expression) STATEMENT

  22. Strings are objects, not arrays of characters • Arrays of characters: • Strings

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

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

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

  26. A Student Model • Person is the general, superclass. • A Person has a name. • Studentis a subclass of Person. • A Student has a student identification number (“id”). • Because Studentinherits 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.

  27. Starting a Definition of Person • Any class can make instances from a public class. • A public field (the Stringname) 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

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

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

  30. Definition #2: Making names private • Now name is private. It can onlybe changed with setName() and read with getName() setName() is void, because it doesn’t return anything.getName() returns a String.

  31. Trying out Definition #2 • Should People have names as soon as they are created?

  32. Definition #3: Using constructors • Constructors are called via Person(), to initialize an object.

  33. Accessing Constructors

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

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

  36. Adding toString() to Person • Now, Person instances can print themselves by name: Strings can be concatenated (combined) with +

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

  38. Student Definition#1: A Student has an ID This goes in a file named Student.java

  39. Using our Student definition

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

  41. Student Definition #2 If you’re going to call the superclass constructor, call super() as the first statement in the constructor.

  42. Trying out Student definition #2

  43. Creating a test method for Person • This method is always called public static void main(String[] args)

  44. Exploring inheritance • A greet() method for Person

  45. Overriding greet() in Student • Can’t just say this.name because name is private.

  46. Variables, Types and Classes • A variable of type superclass can hold any subclass, but not vice-versa.

  47. Accessing subclass parts requires casting

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

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

More Related