Objects, Classes and Applets Computer Programming II Metcalfe County High School Justin Smith-...
Transcript of Objects, Classes and Applets Computer Programming II Metcalfe County High School Justin Smith-...
Objects, Classes and AppletsObjects, Classes and Applets
Computer Programming II
Metcalfe County High School
Justin Smith- Instructor
2
Introduction to ObjectsIntroduction 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
3
Objects and ClassesObjects and Classes
Bank Account
A class(the concept)
John’s Bank AccountBalance: $5,257
An object(the realization)
Bill’s Bank AccountBalance: $1,245,069
Mary’s Bank AccountBalance: $16,833
Multiple objectsfrom the same class
4
The print MethodThe 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)
5
Character StringsCharacter 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.
6
String ConcatenationString 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.
7
Escape SequencesEscape 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.");
8
Escape SequencesEscape 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.
Escape Sequence
\b\t\n\r\"\'\\
Meaning
backspacetab
newlinecarriage returndouble quotesingle quotebackslash
9
AssignmentAssignment
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
10
Assignment 2Assignment 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
11
Assignment 3Assignment 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.
12
VariablesVariables
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
data type variable name
13
VariablesVariables
A variable can be given an initial value in the declaration
When a variable is referenced in a program, its current value is used
int sum = 0;int base = 32, max = 149;
14
AssignmentAssignment
An assignment statement changes the value of a variable The assignment operator is the = sign
total = 55;
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
The expression on the right is evaluated and the result is stored in the variable on the left
15
AssignmentAssignment
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
16
ConstantsConstants
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;
17
Primitive DataPrimitive 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;
18
Arithmetic ExpressionsArithmetic 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
19
Division and RemainderDivision and Remainder
If both operands to the division operator (/) are integers, the result is an integer (the fractional part is discarded)
The remainder operator (%) returns the remainder after dividing the second operand into the first
14 / 3 equals?
8 / 12 equals?
4
0
14 % 3 equals?
8 % 12 equals?
2
8
20
Operator PrecedenceOperator 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
21
Operator PrecedenceOperator Precedence
What is the order of evaluation in the following expressions?
a + b + c + d + e1 432
a + b * c - d / e3 241
a / (b + c) - d % e2 341
a / (b * (c + (d - e)))4 123
22
AssignmentAssignment
Code and Run the program listed on page 77(The temp converter program) when finished please submit for a daily work grade.
23
TestTest
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.
24
Chapter 2------ Part 2Chapter 2------ Part 2
25
Creating ObjectsCreating Objects
Generally, we use the new operator to create an object
title = new String ("Java Software Solutions");
This calls the String constructor, which isa special method that sets up the object
Creating an object is called instantiation
An object is an instance of a particular class
26
Creating ObjectsCreating 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.
27
Class LibrariesClass 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
28
PackagesPackages
The classes of the Java standard class library are organized into packages
Some of the packages in the standard class library are:
Packagejava.appletjava.awtjavax.swing
PurposeCreating applets for the webGraphics and graphical user interfacesAdditional graphics capabilities and components
29
The import DeclarationThe 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.*;
30
The import DeclarationThe 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.
31
The Keyboard ClassThe 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
32
Formatting OutputFormatting 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
33
Assignment 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.
34
Programming ProjectsProgramming 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
35
AppletsApplets
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
36
AppletsApplets
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
37
AssignmentAssignment
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.
38
How Did The Information Show?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
39
Drawing a LineDrawing a Line
X
Y
10
20
150
45
page.drawLine (10, 20, 150, 45);
page.drawLine (150, 45, 10, 20);
or
40
Drawing a RectangleDrawing a Rectangle
X
Y
page.drawRect (50, 20, 100, 40);
50
20
100
40
41
Drawing an OvalDrawing an Oval
X
Y
page.drawOval (175, 20, 50, 80);
175
20
50
80
boundingrectangle
42
Applet Task – 50 point taskApplet 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.
43
The Color ClassThe 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:
Object
Color.blackColor.blueColor.cyanColor.orangeColor.whiteColor.yellow
RGB Value
0, 0, 00, 0, 2550, 255, 255255, 200, 0255, 255, 255255, 255, 0
44
Let’s Set Some ColorLet’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
45
Assignment 1Assignment 1
Code the snowman applet found on page 107
46
Assignment Applet 2Assignment 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
47
Assignment Applet 3Assignment 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
48
Assignment Applet 4Assignment 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
49
Assignment Applet 5Assignment Applet 5
Design a program that draws the front view of a house. The house must contain the following elements of design. A Blue Background (sky) The sun within the background A 2 story house with attached garage (garage can be 1
story) An arched roof (no flat roof homes allowed) At least 4 windows with shutters (2 per window) A front door with door handle A chimney Driveway that run to the attached garage Green Grass in front of the house (this will be a rectangle) A sidewalk that goes to the front door Appropriate colors used throughout the house applet 100 Point Program