490 likes | 501 Views
Learn about objects and classes in computer programming, including their services, interactions, and representations. Explore the use of print methods, string concatenation, escape sequences, variables, and assignment statements.
E N D
Objects, Classes and Applets Computer Programming II Metcalfe County High School Justin Smith- Instructor
Introduction to Objects • An object represents something with which we can interact in a program • An object provides a collection of services that we can tell it to perform for us • A class represents a concept, and an object represents the embodiment of a class
A class (the concept) An object (the realization) John’s Bank Account Balance: $5,257 BankAccount Bill’s Bank Account Balance: $1,245,069 Multiple objects from the same class Mary’s Bank Account Balance: $16,833 Objects and Classes
The print Method • The System.out object provides another service as well • The print method is similar to the println method, except that it does not advance to the next line • Therefore anything printed after a print statement will appear on the same line • The use of print and println is showcased in the coutdown program on page 61 • See Countdown.java (page 61)
Character Strings • The string concatenation operator (+) is used to append one string to the end of another • Code, compile and run the Facts program on page 64 to see the use and implementation of the string concatenation operator.
String Concatenation • The plus operator (+) is also used for arithmetic addition • The function that the + operator performs depends on the type of the information on which it operates • If both operands are strings, or if one is a string and one is a number, it performs string concatenation • If both operands are numeric, it adds them • Code, compile and run the Addition program on page 65 to see the 2 different ways the + operator can be used.
Escape Sequences • What if we wanted to print a double quote character? • The following line would confuse the compiler because it would interpret the second quote as the end of the string System.out.println ("I said "Hello" to you."); • An escape sequence is a series of characters that represents a special character • An escape sequence begins with a backslash character (\), which indicates that the character(s) that follow should be treated in a special way System.out.println ("I said \"Hello\" to you.");
Escape Sequence \b \t \n \r \" \' \\ Meaning backspace tab newline carriage return double quote single quote backslash Escape Sequences • Some Java escape sequences: • Code, compile and run Roses.java (page 67) to see numerous escape sequences and how they can be implemented into a program.
Assignment • Design a program that utilizes only one println statement and provides a brief introduction about yourself. The program must include 3 of the 7 available escape sequences that have been discussed. • The finished program is worth 50 points and should contain appropriate comments
Assignment 2 • Using only the tab escape sequence \t and the println statement design a program that will print out the following column headings first name, last name and hometown and under each column heading include the first and last name of at least 5 people, and their hometown. Please show your finished program when finished(50 point program). An Example is below. First Name Last Name Hometown Justin Smith Center John Doe Edmonton Jane Doe Summer Shade
Assignment 3 • A Table of Student Grades • Write a Java program that prints a table with a list of at least 5 students together with their grades earned (lab points, bonus points, and the total) in the format below. • ///////////////////\\\\\\\\\\\\\\\\\\\ • == Student Points == • \\\\\\\\\\\\\\\\\\\/////////////////// • Name Lab Bonus Total • ---- --- ----- ----- • Joe 43 7 50 • William 50 8 58 • Mary Sue 39 10 49 • 1. Use tab characters to get your columns aligned and you must use the + operator both for addition and string concatenation.
data type variable name Variables • A variable is a name for a location in memory • A variable must be declared by specifying the variable's name and the type of information that it will hold int total; int count, temp, result; Multiple variables can be created in one declaration
Variables • A variable can be given an initial value in the declaration int sum = 0; int base = 32, max = 149; • When a variable is referenced in a program, its current value is used
Assignment • An assignment statement changes the value of a variable • The assignment operator is the = sign total = 55; • The expression on the right is evaluated and the result is stored in the variable on the left • The value that was in total is overwritten • You can assign only a value to a variable that is consistent with the variable's declared type
Assignment • Code, Compile and Run PianoKeys.java (page 68) to see how variables can be implemented. • Code, Compile and Run Geometry.java (page 70). • Design a program that will print out the following using variables and assignment statements. Please refer to the program on page 70(Geometry Program) for additional help. • Number of days in a week EX: The number of days in a week is 7 • Number of months in a year • Number of sides in a pentagon
Constants • A constant is an identifier that is similar to a variable except that it holds one value while the program is active • In Java, we use the final modifier to declare a constant final int MIN_HEIGHT = 69;
Primitive Data • There basic data types used in Java • To represent integers: • int EX: int total = 100; • To represent floating point numbers(decimals): • double EX: double pi=3.14 • To represent characters: • Char EX: char fail = ‘F’; • To represent boolean values(True/False): • Boolean EX boolean game = false;
Arithmetic Expressions • An expression is a combination of one or more operands and their operators • Arithmetic expressions compute numeric results and make use of the arithmetic operators: Addition + Subtraction - Multiplication * Division / Remainder % • If either or both operands associated with an arithmetic operator are floating point, the result is a floating point
Division and Remainder • If both operands to the division operator (/) are integers, the result is an integer (the fractional part is discarded) 4 14 / 3equals? 0 8 / 12equals? • The remainder operator (%) returns the remainder after dividing the second operand into the first 2 14 % 3equals? 8 8 % 12equals?
Operator Precedence • Operators can be combined into complex expressions result = total + count / max - offset; • PEMDAS • Multiplication, division, and remainder are evaluated prior to addition, subtraction, and string concatenation • Arithmetic operators with the same precedence are evaluated from left to right • Parentheses can be used to force the evaluation order
Operator Precedence • What is the order of evaluation in the following expressions? a + b + c + d + e a + b * c - d / e 1 2 3 4 3 1 4 2 a / (b + c) - d % e 2 1 4 3 a / (b * (c + (d - e))) 4 3 2 1
Assignment • Code and Run the program listed on page 77(The temp converter program) when finished please submit for a daily work grade.
Test • We are now finished with the first part of chapter 2. • A test will be given over the covered material. Please use your Ch2 on the go sheet to help prepare for the exam.
Creating Objects • Generally, we use the new operator to create an object title = new String ("Java Software Solutions"); This calls the String constructor, which is a special method that sets up the object • Creating an object is called instantiation • An object is an instance of a particular class
Creating Objects • Because strings are so common, we don't have to use the new operator to create a String object title = "Java Software Solutions"; • This is special syntax that works only for strings • Once an object has been instantiated, we can use the dot operator to invoke its methods title.length() • Refer to page 81 to see the string class and the many methods that the class contains.
Class Libraries • A class library is a collection of classes that we can use when developing programs • The Java standard class library is part of any Java development environment • The System class and the String class are part of the Java standard class library • Other class libraries can be obtained through third party vendors, or you can create them yourself
Package java.applet java.awt javax.swing Purpose Creating applets for the web Graphics and graphical user interfaces Additional graphics capabilities and components Packages • The classes of the Java standard class library are organized into packages • Some of the packages in the standard class library are:
The import Declaration • When you want to use a class from a package, you could use its fully qualified name java.util.Random • Or you can import the class, and then use just the class name import java.util.Random; • To import all classes in a particular package, you can use the * wildcard character import java.util.*;
The import Declaration • The Random class is part of the java.util package • It provides methods that generate pseudorandom numbers • *********************Assignment********************* • ******Create the String Mutation program on page 83 to help showcase the multiple string methods that can be used within the Java language.****** • On page 90 create the random numbers program that requires the import code to be utilized and random numbers be created.
The Keyboard Class • The Keyboard class is NOT part of the Java standard class library • The Keyboard class is part of a package called cs1 • It contains several static methods for reading particular types of data • This class can be used to capture user input such as a name or ask for a number such as a password. • The complete list of Keyboard class functions can be found on page 93 with examples on pages 94 and 95
Formatting Output • The NumberFormat class has static methods that return a formatter object to allow data to be either in a percentage or currency format. getCurrencyInstance() getPercentInstance() • Each formatter object has a method called format that returns a string with the specified information in the appropriate format
Assignment • Code, compile and run the 2 programs found on page 94 and 95 within the java textbook to showcase the power of the Keyboard class(ECHO & QUADRATIC). • Code, Compile and Run the Price.java program on (page 97) • Complete the paint program that will be distributed on Smith’s website. You will be required to calculate the area of a wall and determine the amount of pain needed to paint a room. • The overall point value will be 100 points. • Utilize the Keyboard class and other features that have been demonstrated and practiced during last few sections of this unit.
Programming Projects • Before we explore applets complete the following programming projects from page 117 – 118 to test your skills. Groups of 2 will be used an only one program per group is required. • Complete the following • 2.2 • 2.4 • 2.6 • 2.11 • 2.13
Applets • A Java application is a stand-alone program with a main method (like the ones we've seen so far) • A Java applet is a program that is intended to transported over the Web and executed using a web browser • An applet also can be executed using the appletviewer tool of the Java Software Development Kit or by embedding the code within a web page • An applet doesn't have a main method
Applets • The paint method, for instance, is executed automatically and is used to draw the applet’s contents • public void paint(Graphics page) • The Graphics class has several methods for drawing shapes
Assignment Code the Einstein program on (page 101) This will be your first Applet design. Notice the difference in some of the coding that is used within the Applet compared to the Applications we have completed in class so far. In order for the code to work correctly in JCreator you may need to use Build File and then Run Project to make the applet show up correctly. Leave your Einstein program open to use in a discussion.
How Did The Information Show? • Think about your Einstein Applet code and answer the following question. • How did the program know where to place my items within the program? • Looking at page 104 and your program code lets generate some answers and examples. • Java uses a grid system of X and Y coordinates within the Java Applet screen. • Using the supplied grid sheet lets diagram out the program to see how it worked. • Shapes with curves, like an oval, are usually drawn by specifying the shape’s bounding rectangle
X Y page.drawLine (10, 20, 150, 45); or page.drawLine (150, 45, 10, 20); Drawing a Line 10 150 20 45
X 40 100 Y Drawing a Rectangle 50 20 page.drawRect (50, 20, 100, 40);
X 80 50 Y Drawing an Oval 175 20 bounding rectangle page.drawOval (175, 20, 50, 80);
Applet Task – 50 point task • Grid out an Applet that will showcase the following shapes within your program. • Circle, Square, Rectangle, Line and the challenging Arc(use page 104 and 105 to assist) the dimensions are up to each programmer and how they wish to layout the applet. • Use Text to Identify each item from above. The identification can be below, above or to the side of the item being created. • Example Square • After the grid design is complete, now code your applet into Jcreator to ensure that we can take project from the grid paper into program design. Refer to the Einstein program and page 104 for code assistance.
Object Color.black Color.blue Color.cyan Color.orange Color.white Color.yellow RGB Value 0, 0, 0 0, 0, 255 0, 255, 255 255, 200, 0 255, 255, 255 255, 255, 0 The Color Class • A color is defined in a Java program using an object created from the Color class • The Color class also contains several static predefined colors, including:
Let’s Set Some Color • To set the page background code similar to: • setBackground (Color.orange); • To set the color of a shape or multiple shapes insert the following before the shape is created. • Page.setColor (Color.black); • Or you can use the new color code. • Java has a set of colors but what if you need a darker or lighter color. • Never fear the new color code is here. • page.setColor (new Color(255,255,255)); • Lets look at an RGB color chart using google.com
Assignment 1 • Code the snowman applet found on page 107
Assignment Applet 2 • Using your snowman applet add the following items into the picture. • Add 3 black buttons into the center of the snowman • Change the color of the ground to black • Add yellow rays coming from the sun 3-4 diagonal lines • Add white circular snowflakes in the background (15-20 snowflakes spread out over the screen) • If needed use the Java grid system to code in the snowman program. • 100 point enhancement
Assignment Applet 3 • Design an applet that draws a smiling face. Give the face a nose, ears, a mouth, and eyes with pupils. • 50 point program
Assignment Applet 4 • Design a program that draws a side view of a car, truck or van. The vehicle will be a combination of various Java ovals, rectangles, lines, arc’s and will utilize various colors to accomplish the task of creating the side view of a vehicle. • 100 Points
Assignment Applet 5 • Design a program that draws the front view of a house. • The house must contain the following elements of design. • vA Blue Background (sky) • vThe sun within the background • vA 2 story house with attached garage (garage can be 1 story) • vAn arched roof (no flat roof homes allowed) • vAt least 4 windows with shutters (2 per window) • vA front door with door handle • vA chimney • vDriveway that run to the attached garage • vGreen Grass in front of the house (this will be a rectangle) • vA sidewalk that goes to the front door • Appropriate colors used throughout the house applet • 100 Point Program