Chapter 4: Writing Classes Objects An object has: • state - descriptive characteristics • behaviors - what it can do (or what can be done to it) For example, consider a coin that can be flipped so that it's face shows either "heads" or "tails" The state of the coin is its current face (heads or tails) The behavior of the coin is that it can be flipped 2 Classes A class is a blueprint of an object It is the model or pattern from which objects are created For example, the String class is used to define String objects 3 Classes The String class was provided for us by the Java standard class library But we can also write our own classes that define specific objects that we need Classes can originate from the following sources • Corporate Sources • Individual programmers like yourself For example, suppose we want to write a program that simulates the flipping of a coin We can write a Coin class to represent a coin object Classes A class contains data declarations and method declarations int x, y; char ch; Data declarations Method declarations The Coin Class In our Coin class we could define the following data: • face, an integer that represents the current face • HEADS and TAILS, integer constants that represent the two possible states We might also define the following methods: • a Coin constructor, to initialize the object • a flip method, to flip the coin • a isHeads method, to determine if the current face is heads • a toString method, to return a string description for printing The Coin Class Code Coin.java (page 194) within BlueJ and compile but do not try to run since the Coin class will be used inside the CountFlips program Code the CountFlips.java into a new class and code the countflips program. Compile and then run the Countflips program. If errors are encountered please make sure the coin class is showing up within your project file(where CountFlips is located). The CountFlips program uses the Coin class that was created on page 194 Turn in for a 100 point grade when finished. Save the Coin class for later use. Count Flips Modified Using the CountFlips.java program modify the program to do the following. • Prompt the user for the number of coin flips they would like to have completed. • Program should print out the % of times the flip was heads or tails. Example Heads- 55% Tails-45% Data Scope The scope of data is the area in a program in which that data can be used (referenced) Data declared at the class level can be used by all methods in that class Data declared within a method can be used only in that method Data declared within a method is called local data Instance Data The face variable in the Coin class is called instance data because each instance (object) of the Coin class has its own storage space. Every time a Coin object is created, a new face variable is created as well because each coin will contain the value of either Heads or Tails. Instance Data Code and compile the FlipRace.java (page 197) You will need to include(insert) the Coin class within this program in order for FlipRace to work correctly. If the Coin class is not included an error will be produced within FlipRace that will highlight the word Coin showcasing that the program does not know where the Coin class is located at. Add the following to the FlipRace program 100 point grade 1)Allow the user to guess either Heads or Tails before the flip result is displayed.(Ask the question first, next read the string or integer(user could type h for heads and t for tails or someone could even have the user to type 1 for heads and 2 for tails), finally use an if-else statement to determine if the guess was correct or not.) 2)When the program ends tell the user how many times he/she guessed both coin flips correctly. Visibility Modifiers A modifier is a Java reserved word that specifies particular characteristics of a method or data value We've used the modifier final to define a constant We will study two visibility modifiers: public and private 13 Driver Programs A driver program drives the use of other, more interesting part or parts of a program such as a class. Driver programs can access multiple classes and perform multiple operations with very little code. Driver Programs Code and Compile Account.java (page 204) The above program is a class that has multiple functions that can be used in other programs. Such as the Banking program from below. Code, Compile and Run Banking.java (page 202) The above program cannot function without the Account.java program code. This is the driver program. Driver Programs Lets enhance the Banking program in groups of 2. Add the following to the Banking.java program 200 point project. • Ask the user to enter an account number either 72354, 69713 or 93757 • After a correct account number is entered ask the user if they wish to withdraw or deposit money within the account. • Allow the user to either withdraw or deposit funds. • Once the withdraw or deposit is made print out the new account balance. • Allow the program to continue until the user wises to quit(a loop may be needed). The return Statement The return type of a method indicates the type of value that the method sends back to the calling location A method that does not return a value has a void return type A return statement specifies the value that will be returned return expression; Its expression must conform to the return type 17 Parameters Each time a method is called, the actual parameters in the invocation are copied into the formal parameters ch = obj.calc (25, count, "Hello"); char calc (int num1, int num2, String message) { int sum = num1 + num2; char result = message.charAt (sum); return result; } A Parameter is a value or values sent into the class in order for the class to operate. Overloading Methods Code, SnakeEyes.java (page 212) Code the class and Compile Die.java (page 213) Run the SnakeEyes program Group Work(2per group)- 50 points Add The Following To The SnakeEyes Program *Change the program where it asks the user if he/she would like to roll the die, Y to roll, N to quit. *After each attempt have the program display the value for each die. *Have the program display the number of rolls and number of snake eyes. 19 Pig Latin The process of translating an English sentence into Pig Latin can be decomposed into the process of translating each word The process of translating a word can be decomposed into the process of translating words that • begin with vowels • begin with consonant blends (sh, cr, tw, etc.) • begins with single consonants Pig Latin 50 Point Program Code and Compile PigLatinTranslator.java (page 216) Code, Compile and Run PigLatin.java (page 215) Aggregation An aggregate object is an object that contains references to other objects For example, an Account object contains a reference to a String object (the owner's name) An aggregate object represents a has-a relationship A bank account has a name Likewise, a student may have one or more addresses Aggregation 100 Point Program Code and Compile Student.java (page 227) Code and Compile Address.java (page 228) Code, Compile and Run StudentBody.java (page 226) Add the Following- Group Project(2 per group) 100 Points *Have the program ask which user record needs to be printed at the end of the program by the first name being entered. Create variables to allow the user to enter in a new student and new address, a variable will need to be created for each item that is included in the current program. Programming Projects Projects from pages 243-244 Complete in groups of 2 – 150 points each. Choose 1 of the following • 4.2 • 4.3 • 4.4 Applet Methods In previous examples we've used the paint method of the Applet class to draw on an applet The Applet class has several methods that are invoked automatically at certain points in an applet's life The init method, for instance, is executed only once when the applet is initially loaded The start and stop methods are called when the applet becomes active or inactive The Applet class also contains other methods that generally assist in applet processing Graphical Objects Any object we define by writing a class can have graphical elements The object must simply obtain a graphics context (a Graphics object) in which to draw An applet can pass its graphics context to another object just as it can any other parameter Applet 50 Point Program Code and Compile StickFigure.java (page 235) Code, Compile and Run LineUp.java (page 233) 100 point addition to the above program • Add 5 more stick people to the program using various colors • Add a background image of House and Tree or Grass, Flowers, Pond or Birds, Sun, Clouds. Applet Applet • Design an applet that draws a box of crayons. The crayon box must contain at least 6 crayons. Use the new color code to make custom colored crayons and the drawstring code to put a name on each and even the box. Crayons can be both inside and outside the box within the applet. Applet Using your applet knowledge and Java code knowledge design an applet view of a CITY. • The City must have at least 5 buildings with windows & various sizes(you determine the size and how the buildings need to look).(50pts) • A sidewalk or sidewalks (can be in front of your buildings, at an angle, beside your roadway, etc) (25pts) • A Roadway or multiple roads (can be anywhere within the city) with appropriate yellow lines. (25pts) • A sign that welcomes people to the city (You are to name the city) (15pts) • At least one car must be inserted into the program (this can be a rectangle car if you wish) (25pts) • A park with a bench, swing set, monkey bars, pond, parking area and walking trail (75 pts) • A skyline (you decide if it is day or night) (10pts) • One addition that you decide is appropriate for your city. (25pts) • Graphical and organizational appeal of the designed city (50pts) Applet is worth a 300 point test grade, due date will be announced.