To understand the difference between objects and object references
To write programs that display simple shapes
Objects and Classes
Each part a home builder uses,
such as a furnace or a water heater,
fulfills a particular function. Similarly,
you build programs from objects, each
of which has a particular behavior.
In Java, you build programs for objects.
Each object has certain behaviors.
You can manipulate the object to get certain effects.
Using Objects
Object: an entity in your program that you can manipulate by calling one or more of its methods.
Method: consists of a sequence of instructions that can access the data of an object.
You do not know what the instructions are
You do know that the behavior is well defined
System.out has a println method
You do not know how it works
What is important is that it does the work you request of it
Figure 1 Representation of the System.out Object
Using Objects
You can think of a water heater as an object that can carry out the "get
hot water" method. When you call that method to enjoy a hot shower, you don't care whether the water heater uses gas or solar power.
Classes
A class describes a set of objects with
the same behavior.
Some string objects
"Hello World" "Goodbye" "Mississippi"
You can invoke the same methods on all strings.
System.out is a member of the PrintStream class that writes to the console window.
You can construct other objects of PrintStream class that write to different destinations.
All PrintStream objects have methods println and print.
Classes
Objects of the PrintStream class have a completely different behavior
than the objects of the String class.
Different classes have different responsibilities
A string knows about the letters that it contains
A string doesn't know how to send itself to a console window or file.
All objects of the Window class share the same behavior.
Self Check 2.1
In Java, objects are grouped into classes according to their behavior. Would a
window object and a water heater object belong to the same class or to different
classes? Why?
Answer:
Objects with the same behavior belong to
the same class. A window lets in light while
protecting a room from the outside wind and
heat or cold. A water heater has completely
different behavior. It heats water. They belong
to different classes.
Self Check 2.2
Some light bulbs use a glowing filament, others use a fluorescent gas. If you
consider a light bulb a Java object with an "illuminate" method, would you need
to know which kind of bulb it is?
Answer:
When one calls a method, one is not concerned
with how it does its job. As long as a light bulb
illuminates a room, it doesn't matter to the
occupant how the photons are produced.
Variables
Use a variable to store a value that you want to use later
To declare a variable named width
int width = 20;
Like a variable in a computer
program, a parking space has
an identifier and a contents.
Syntax 2.1 Variable Declaration
Variables
A variable is a storage location
Has a name and holds a value
When declaring a variable, you usually specify an initial value.
When declaring a variable, you also specify the type of its values.
Variable declaration: int width = 20:
width is the name
int is the type
20 is the initial value
Each parking space is suitable for a particular type of vehicle,
just as each variable holds a value of a particular type.
Variable Declarations
Types
Use the int type
for numbers that
cannot have a
fractional part.
int width = 20;
Use the double type for floating point numbers.
double milesPerGallon = 22.5;
Numbers can be combined by arithmetic operators such as +, -, and *
Another type is String
String greeting = "Hello";
A type specifies the operations that can be carried out with its values.
You can multiply the value width holds by a number
You can not multiply greetings by a number.
Names
Pick a name for a variable that describes its purpose.
Rules for the names of variables, methods, and classes:
Must start with a letter or the underscore (_) character, and the remaining characters must be letters, numbers, or underscores.
Cannot use other symbols such as ? or %
or a space
Use uppercase letters to denote word boundaries, as in milesPerGallon. (Called
camel case)
Names are case sensitive
You cannot use reserved words such as double or class
By Java convention:
variable names start with a lowercase letter.
class names start with an uppercase letter.
Variable Names in Java
Comments
Use comments to add explanations for humans who read your code.
double milesPerGallon = 33.8; // The average fuel efficiency of new U.S. cars in 2011
The compiler does not process comments
It ignores everything from a // delimiter to the end of the line.
For longer comment, enclose it between /* and */ delimiters.
The compiler ignores these delimiters and everything in between.
Example of longer comments
/*
In most countries, fuel efficiency is measured in liters per hundred
kilometer. Perhaps that is more useful—it tells you how much gas you need
to purchase to drive a given distance. Here is the conversion formula.
*/
double fuelEfficiency = 235.214583 / milesPerGallonS
Assignment
Use the assignment operator (=) to change the value of a variable.
You have the following variable declaration
int width = 10;
To change the value of the variable, assign the new value
width = 20;
Figure 2 Assigning a New Value to a Variable
Assignment
It is an error to use a variable that has never had a value assigned to it:
int height;
int width = height; // ERROR - uninitialized variable height
The compiler will complain about an "uninitialized variable"
Figure 3 An Uninitialized Variable
Remedy: assign a value to the variable before you use it.
int height = 20;
int width = height; // OK
All variables must be
initialized before you
access them.
Assignment
The right-hand side of the = symbol can be a mathematical expression:
width = height + 10;
This means
compute the value of height + 10
store that value in the variable width
width = width + 10
The assignment operator = does not denote mathematical equality.
Figure 4 Executing the Statement width = width + 10
Syntax 2.2 Assignment
Self Check 2.3
What is wrong with the following variable declaration?
int miles per gallon = 39.4
Answer:
There are three errors:
You cannot have spaces in variable names.
The variable type should be double because it
holds a fractional value.
There is a semicolon missing at the end of the
statement.
Self Check 2.4
Declare and initialize two variables, unitPrice and quantity, to contain the unit
price of a single item and the number of items purchased. Use reasonable initial
values.
Answer:
double unitPrice = 1.95;
int quantity = 2;
Self Check 2.5
Use the variables declared in Self Check 4 to display the total purchase price.
Example: public String replace(String target, String replacement)
Has two arguments, target and replacement
Both arguments have type String
The returned value is another string
Example: public void println(String output)
Has an argument of type String
No return value
Uses the keyword void
Method Declaration
A class can declare two methods with the same name and different argument types.
The PrintStream class declares another println method
public void println(int output)
Used to print an integer value
The println name is overloaded because it refers to more than one method.
Self Check 2.13
How can you compute the length of the string "Mississippi"?
Answer:river.length() or "Mississippi".length()
Self Check 2.14
How can you print out the uppercase version of "Hello, World!"?
Answer: System.out.println(greeting.toUpperCase()); Or System.out.println("Hello, World!".toUpperCase());
Self Check 2.15
Is it legal to call river.println()? Why or why not?
Answer:
It is not legal. The variable river has type String. The println
method is not a method of the String class.
Self Check 2.16
What are the arguments in the method call river.replace("p", "s")?
Answer:
The arguments are the strings "p" and "s".
Self Check 2.17
What is the result of the call river.replace("p", "s"), where river is "Mississippi"?
Answer: "Missississi"
Self Check 2.18
What is the result of the call greeting.replace("World", "Dave").length(), where greeting is "Hello, World!"?
Answer:
12
Self Check 2.19
How is the toUpperCase method declared in the String class?
Answer:
As public String toUpperCase(), with no argument and return type String.
Constructing Objects
Objects of the Rectangle class describe rectangular shapes.
Constructing Objects
The Rectangle object is not a rectangular shape.
It is an object that contains a set of numbers.
The numbers describe the rectangle
Each rectangle is described by:
The x- and y-coordinates of its top-left corner
Its width
And its height.
Constructing Objects
In the computer, a Rectangle object is a block of memory that holds four numbers.
Constructing Objects
Use the new
operator, followed
by a class name
and arguments,
to construct
new objects.
new Rectangle(5, 10, 20, 30)
Detail:
The new operator makes a Rectangle object
It uses the parameters (in this case, 5, 10, 20, and 30)
to initialize the data of the object
It returns the object
The process of creating a new object is called construction.
The four values 5, 10, 20, and 30 are called the construction arguments.
Usually the output of the new operator is stored in a variable:
Rectangle box = new Rectangle(5, 10, 20, 30);
Additional constructor
new Rectangle()
Syntax 2.3 Object Construction
Self Check 2.20
How do you construct a square with center (100, 100) and side length 20?
Answer:
new Rectangle(90, 90, 20, 20)
Self Check 2.21
Initialize the variables box and box2 with two rectangles that touch each other.
Answer:
Rectangle box = new Rectangle(5, 10, 20, 30);
Rectangle box2 = new Rectangle(25, 10, 20, 30);
Self Check 2.22
The getWidth method returns the width of a Rectangle object. What does the following statement print?
System.out.println(new Rectangle().getWidth());
Answer:
0
Self Check 2.23
The PrintStream class has a constructor whose argument is the name of a file.
How do you construct a PrintStream object with the construction argument
"output.txt"?
Answer:new PrintStream("output.txt");
Self Check 2.24
Write a statement to save the object that you constructed in Self Check 23 in a
variable.
Answer:PrintStream out = new PrintStream("output.txt");
Accessor and Mutator Methods
Accessor method: does not change the internal data of the object
on which it is invoked.
Figure 13 The API Documentation of the Standard Java Library
Locate Rectangle link in the left pane
Click on the link
The right pane shows all the features of the Rectangle class
Browsing the API Documentation - Method Summary
Figure 14 The Method Summary for the Rectangle Class
The API documentation for each class has
A section that describes the purpose of the class
Summary tables for the constructors and methods
Clicking on a method's link leads to a detailed description of the method
Browsing the API Documentation
The detailed description of a method shows:
The action that the method carries out
The types and names of the parameter variables that receive the arguments when the method is called
The value that it returns (or the reserved word void if the method doesn't return any value).
Packages
Java classes are
grouped into
packages.
The Rectangle class belongs to the package java.awt.
To use the Rectangle class you must import the package:
import java.awt.Rectangle;
Put the line at the top of your program.
You don't need to import classes in the java.lang package such as String
and System.
Syntax 2.4 Importing a Class from a Package
Self Check 2.30
Look at the API documentation of the String class. Which method would
you use to obtain the string "hello, world!" from the string "Hello,
World!"?
Answer:toLowerCase
Self Check 2.31
In the API documentation of the String class, look at the description
of the trim method. What is the result of applying trim to the string
" Hello, Space ! "? (Note the spaces in the string.)
Answer:"Hello, Space !" – only the leading and trailing spaces are
trimmed.
Self Check 2.32
Look into the API documentation of the Rectangle class. What is the difference between the methods void translate(int x, int y) and void setLocation(int x, int y)?
Answer: The arguments of the translate method tell
how far to move the rectangle in the x- and
y-directions. The arguments of the setLocation
method indicate the new x- and
y-values for
the top-left corner.
For example, box.translate(1, 1) moves the box
one pixel down and to the right. box.setLocation(
1, 1) moves box to the top-left corner of
the screen.
Self Check 2.33
The Random class is declared in the java.util package. What do
you need to do in order to use that class in your program?
Answer:
Add the statement
import java.util.Random;
at the top of your program.
Self Check 2.34
In which package is the BigInteger class located? Look it up in the API documentation.
Answer:
In the java.math package
Implementing a Test Program
A test program
verifies that methods
behave as expected.
Steps in writing a tester class
Provide a tester class.
Supply a main method.
Inside the main method, construct one or more objects.
Apply methods to the objects.
Display the results of the method calls.
Display the values that you expect to get.
Implementing a Test Program
Code to test the behavior of the translate method
Rectangle box = new Rectangle(5, 10, 20, 30);
// Move the rectangle
box.translate(15, 25);
// Print information about the moved rectangle
System.out.print("x: ");
System.out.println(box.getX());
System.out.println("Expected: 20");
Place the code
inside the main method of the MoveTester class
Determining the
expected result
in advance is an
important part
of testing.
What is the effect of the assignment greeting2 = greeting?
Answer:
Now greeting and greeting2 both refer to the same String
object.
Self Check 2.38
After calling greeting2.toUpperCase(), what are the contents of greeting
and greeting2?
Answer:
Both variables still refer to the same string, and the string has not been
modified. Recall that the toUpperCase method constructs a new string
that contains uppercase characters, leaving the original string unchanged.
Mainframe Computer
Mainframe Computer
Graphical Applications: Frame Windows
A graphical application shows
information inside a frame.
Answer:
Construct two JFrame objects, set each of their sizes, and call setVisible(true)
on each of them.
Self Check 2.41
How do you modify the program to draw two squares?
Answer:Rectangle box = new Rectangle(5, 10, 20, 20);
Self Check 2.42
How do you modify the program to draw one rectangle and one square?
Answer:
Replace the call to box.translate(15, 25) with
box = new Rectangle(20, 35, 20, 20);
Self Check 2.43
What happens if you call g.draw(box) instead of g2.draw(box)?
Answer:
The compiler complains that g doesn't have a draw method.
Ellipses
To construct an ellipse, you specify its bounding box.
Figure 22 An Ellipse and Its Bounding Box
To construct an Ellipse:
Ellipse2D.Double ellipse = new Ellipse2D.Double(x, y, width, height);
Ellipses
Ellipse2D.Double is an inner class — doesn't matter to us except for the import
statement:
import java.awt.geom.Ellipse2D; // No .Double
To draw the shape:
g2.draw(ellipse);
Circles
To draw a circle, set the width and height to the same values:
Ellipse2D.Double circle = new Ellipse2D.Double(x, y, diameter, diameter);
g2.draw(circle);
(x, y) is the top-left corner of the bounding box, not the center of the
circle.
Lines
To draw a line, specify its end points:
Line2D.Double segment = new Line2D.Double(x1, y1, x2, y2);
g2.draw(segment);
or
Point2D.Double from = new Point2D.Double(x1, y1);
Point2D.Double to = new Point2D.Double(x2, y2);
Line2D.Double segment = new Line2D.Double(from, to);
g2.draw(segment);
Drawing Text
To draw text, use the drawString method
Specify the string and the x- and y-coordinates of the basepoint of the first character
g2.drawString("Message", 50, 100);
Figure 23 Basepoint and Baseline
Colors
To draw in color, you need to supply a Color
object.
Specify the amount of red, green, blue as values between 0 and 255:
Color magenta = new Color(255, 0, 255);
The Color class declares a variety of colors:
Color.BLUE, Color.RED, Color.PINK etc.
To draw a shape in a different color
First set color in graphics context:
g2.setColor(Color.Red);
g2.draw(circle); // Draws the shape in red
Colors - continued
To color the inside of the shape, use the fill method:
g2.fill(circle); // Fills with current color
When you set a new
color in the graphics
context, it is used for
subsequent drawing
operations.