Title: Overview Java CHAPTERS 2,3,4,7,11,12
1Overview JavaCHAPTERS 2,3,4,7,11,12
- AN INTRODUCTION TO OBJECTS AND CLASSES
2Chapter Goals
- To understand the concepts of classes and objects
- To realize the difference between objects and
object references - To become familiar with the process of
implementing classes - To be able to implement simple methods
- To understand the purpose and use of constructors
- To understand how to access instance fields and
local variables - To appreciate the importance of documentation
comments
3Objects and Classes
- Object entity that you can manipulate in your
programs (by invoking methods) - Each object belongs to a class
- Class Set of objects with the same behavior
- Class determines legal methods"Hello".println()
// Error"Hello".length() // OK
4Rectangle Class
- Construct a rectanglenew Rectangle(5, 10, 20,
30)new Rectangle() - Use the constructed objectSystem.out.println(new
Rectangle(5, 10, 20, 30))prints
java.awt.Rectanglex5,y10,width20,height30
5Rectangle Shapes
6A Rectangle Object
7Syntax 2.1 Object Construction
- new ClassName(parameters)
- Example
- new Rectangle(5, 10, 20, 30)
- new Car("BMW 540ti", 2004)
- Purpose
- To construct a new object, initialize it with the
construction parameters, and return a reference
to the constructed object.
8Object Variables
- Declare and optionally initializeRectangle
cerealBox new Rectangle(5, 10, 20,
30)Rectangle crispyCrunchy - Apply methodscerealBox.translate(15, 25)
- Share objectsr cerealBox
9Uninitialized and Initialized Variables
Uninitialized
Initialized
10Two Object Variables Referring to the Same Object
11Syntax 2.2 Variable Definition
- TypeName variableName
- TypeName variableName expression
- Example
- Rectangle cerealBox String name "Dave"
- Purpose
- To define a new variable of a particular type
- and optionally supply an initial value
12Writing a Test Program
- Invent a new class, say MoveTest
- Supply a main method
- Place instructions inside the main method
- Import library classes by specifying the package
and class nameimport java.awt.Rectangle - You don't need to import classes in the java.lang
package such as String and System
13Syntax 2.3 Importing a Class from a Package
- importpackageName.ClassName
- Example
- import java.awt.Rectangle
- Purpose
- To import a class from a package for use in a
program
14File MoveRect.java
- 1 import java.awt.Rectangle
- 2
- 3 public class MoveTest
- 4
- 5 public static void main(String args)
- 6
- 7 Rectangle cerealBox new Rectangle(5,
- 10, 20, 30)
- 8 // move the rectangle
- 9 cerealBox.translate(15, 25)
- 10 // print the moved rectangle
- 11 System.out.println(cerealBox)
- 12
15A Simple Class
- public class Greeter public String
sayHello() String message
"Hello,World!" return message
16Method Definition
- access specifier (such as public)
- return type (such as String or void)
- method name (such as sayHello)
- list of parameters (empty for sayHello)
- method body in
17Method Parameters
- public class Rectangle . . . public void
translate(int x, int y) method body
. . .
18Syntax 2.4 Method Implementation
- public class ClassName ...
accessSpecifier returnType methodName(parameterTyp
e parameterName,...) method body
...
Continue
19- Continue
- Example
- public class Greeter public String
sayHello() String message
"Hello,World!" return message - Purpose
- To define the behavior of a method A method
definition specifies the method name, parameters,
and the statements for carrying out the method's
actions
20Syntax 2.5 The return Statement
- return expression
- or
- return
- Example
- return message
- Purpose
- To specify the value that a method returns, and
- exit the method immediately. The return value
- becomes the value of the method call
- expression.
21Testing a Class
- Test class a class with a main method that
contains statements to test another class. - Typically carries out the following steps
- Construct one or more objects of the class that
is being tested. - Invoke one or more methods.
- Print out one or more results
22A Test Class for the Greeter Class
- public class GreeterTest
- public static void main(String args))
Greeter worldGreeter new Greeter()
- System.out.println(worldGreeter.sayHello())
-
-
23Building a Test Program
- 1. Make a new subfolder for your program.
- 2. Make two files, one for each class.
- 3. Compile both files.
- 4. Run the test program.
24Testing with the SDK Tools
- mkdir greeter
- cd greeter
- edit Greeter.java
- edit GreeterTest.java
- javac Greeter.java
- javac GreeterTest.java
- java GreeterTest
25Testing with BlueJ
26Instance Fields
- public class Greeter
- ...private String name
-
- access specifier (such as private)
- type of variable (such as String)
- name of variable (such as name)
27Instance Fields
28Accessing Instance Fields
- The sayHello method of the Greeter class can
access the private instance fieldpublic String
sayHello()String message "Hello, " name
"!"return message
29- Other methods cannotpublic class
GreeterTestpublic static void main(String
args). . .System.out.println(daveGreeter.name)
// ERROR - Encapsulation Hiding data and providing access
through methods
30Syntax 2.6 Instance Field Declaration
- accessSpecifier class ClassName ...
accessSpecifier fieldType fieldName ...
31- Example
- public class Greeter ... private
String name ... - Purpose
- To define a field that is present in every object
of a class
32Constructors
- A constructor initializes the instance variables
- Constructor name class name
- public class Greeter() public Greeter(String
aName) name aName . . . - Invoked in new expressionnew Greeter("Dave")
33Syntax 2.7 Constructor Implementation
- accessSpecifier class ClassName ...
accessSpecifier ClassName(parameterTypeparameterN
ame ...) constructor implementation
...
34- Example
- public class Greeter ... public
Greeter(String aName) name aName
... - Purpose
- To define the behavior of a constructor, which is
used to initialize the instance fields of newly
created objects
35File Greeter.java
- 1 public class Greeter
- 2
- 3 public Greeter(String aName)
- 4
- 5 name aName
- 6
- 7
- 8 public String sayHello()
- 9
36- 10 String message "Hello, " name "!"
- 11 return message
- 12
- 13
- 14 private String name
- 15
37File GreeterTest.java
- 1 public class GreeterTest
- 2
- 3 public static void
- main(String args)
- 4
- 5 Greeter worldGreeter new Greeter("World")
- 6System.out.println(worldGreeter.sayHello())
- 7
38- 8 Greeter daveGreeter new Greeter("Dave")
- 9System.out.println(daveGreeter.sayHello())
- 10
- 11
39Designing the Public Interface
- Behavior of bank account
- deposit money
- withdraw money
- get balance
- Methods of BankAccount class
- deposit
- withdraw
- getBalance
40BankAccount Public Interface
- public BankAccount()
- public BankAccount(double initialBalance)
- public void deposit(double amount)
- public void withdraw(double amount)
- public double getBalance()
41Using the Public Interface
- Transfer balance
- double amt 500momsSavings.withdraw(amt)harry
sChecking.deposit(amt) - Add interest
- double rate 5 // 5double amt
acct.getBalance() rate / 100acct.deposit(am
t)
42Commenting the Public Interface
- / Withdraws money from the bank account.
_at_param the amount to withdraw / public void
withdraw(double amount) implementation filled
in later
43- / Gets the current balance of the bank
account. _at_return the current balance / public
double getBalance() implementation filled in
later
44Class Comment
- / A bank account has a balance that can
be changed by deposits and withdrawals. /
public class BankAccount ...
45Javadoc Method Summary
46Javadoc Method Detail
47BankAccount Class Implementation
- Determine instance variables to hold object
stateprivate double balance - Implement methods and constructors
48File BankAccount.java
- 1 /
- 2 A bank account has a balance that can be
changed by - 3 deposits and withdrawals.
- 4 /
- 5 public class BankAccount
- 6
49- 7 /
- 8 Constructs a bank account with a zero balance
- 9 /
- 10 public BankAccount()
- 11
- 12 balance 0
- 13
- 14
50- 15 /
- 16 Constructs a bank account with a given balance
- 17 _at_param initialBalance the initial balance
- 18 /
- 19 public BankAccount(double initialBalance)
- 20
- 21 balance initialBalance
- 22
51- 23
- 24 /
- 25 Deposits money into the bank account.
- 26 _at_param amount the amount to deposit
- 27 /
- 28 public void deposit(double amount)
- 29
- 30 double newBalance balance amount
- 31 balance newBalance
- 32
- 33
52- 34 /
- 35 Withdraws money from the bank account.
- 36 _at_param amount the amount to withdraw
- 37 /
- 38 public void withdraw(double amount)
- 39
- 40 double newBalance balance - amount
- 41 balance newBalance
- 42
- 43
53- 44 /
- 45 Gets the current balance of the bank account.
- 46 _at_return the current balance
- 47 /
- 48 public double getBalance()
- 49
- 50 return balance
- 51
- 52
- 53 private double balance
- 54
54File BankAccountTest.java
- 1 /
- 2 A class to test the BankAccount class.
- 3 /
- 4 public class BankAccountTest
- 5
- 6 /
- 7 Tests the methods of the BankAccount class.
- 8 _at_param args not used
- 9 /
55- 10 public static void main(String args)
- 11
- 12 BankAccount harrysChecking new
BankAccount() - 13 harrysChecking.deposit(2000)
- 14 harrysChecking.withdraw(500)
- 15 System.out.println(harrysChecking.getBalance())
- 16
- 17
56Calling a Method in BlueJ
57The Method Return Value in BlueJ
58Variable Types
- Instance fields (balance in BankAccount)
- Local variables (newBalance in deposit method)
- Parameter variables (amount in deposit method)
59Explicit and Implicit Parameters
- public void withdraw(double amount) double
newBalance balance - amount balance
newBalance - balance is the balance of the object to the left
of the dot - momsSavings.withdraw(500)
- means
- double newBalance momsSavings.balance -
amount momsSavings.balance newBalance
60Chapter 4
61Chapter Goals
- To be able to write simple applets
- To display graphical shapes such as lines and
ellipses - To use colors
- To display text in multiple fonts
- To select appropriate units for drawing
- To develop test cases that validate the
correctness of your programs
62Console Application
63Graphical Application
64Applets
- Graphical Java programs
- Run inside web browser
- Platform-neutral
- Easy deployment--loads when needed
- Secure
65Web Browsers Accessing a Web Server
66A Web Browser
67Brief Introduction to HTML
- Text and tagsJava is an ltigtobject-orientedlt/igt
programming language - Browser renders the tagsJava is an
object-oriented programming language - Bulleted list (like this one) is defined by
tagsltulgtltligt. . .lt/ligtltligt. . .lt/ligtltligt. .
.lt/ligtlt/ulgt - Use ltgt for ltgt symbols
68Images, Links and Applets
- Image tag has attributes source, size, alternate
textltimg src"hamster.jpeg" width"640"
height"480"alt"A photo of Harry, the horrible
hamster" /gt - Link tag has attribute for link, body for linked
textlta href"http//java.sun.comgtJavalt/agt is an
. . . - Applets need class for applet code and
sizeltapplet code"HamsterApplet.class"width"64
0" height"480"gt
69Viewing an Applet
- Make one or more Java source files to implement
your applet - One of the source files must define the applet
class - Compile the source files into class files
- Make an HTML file with the applet tag that
references the applet class - Run appletviewer myapplet.html
- Or load the HTML file into a Java 2 compliant
browser
70The RectangleApplet in the Applet Viewer
71The RectangleApplet in a Browser
72Applet Class Outline
- class MyApplet extends Applet
- public void paint(Graphics g)Graphics2D g2
(Graphics2D)g// add drawing operations. . .
73File RectangleApplet.java
- 1import java.applet.Applet
- 2import java.awt.Graphics
- 3import java.awt.Graphics2D
- 4import java.awt.Rectangle
- 5
- 6/
- 7 An applet that draws two rectangles.
- 8/
- 9public class RectangleApplet extends Applet
- 10
- Continue
74- 11 public void paint(Graphics g)
- 12
- 13 // recover Graphics2D
- 14
- 15 Graphics2D g2 (Graphics2D)g
- 16
- 17 // construct a rectangle and draw it
- 18
- 19 Rectangle cerealBox new Rectangle(5, 10,
20, 30) - 20 g2.draw(cerealBox)
- 21
- 22 // move rectangle 15 units sideways and 25 uni
ts down - 23 Continue
75- 24 cerealBox.translate(15, 25)
- 25
- 26 // draw moved rectangle
- 27
- 28 g2.draw(cerealBox)
- 29
- 30
76Graphical Shapes
- Shape classes Ellipse2D.Double, Line2D.Double,
etc. - We won't use the .Float classes
- These classes are inner classes--doesn't matter
to us except for the import statementimport
java.awt.geom.Ellipse2D // no .Double - Must construct and draw the shape
Ellipse2D.Double easterEgg new
Ellipse2D.Double(5, 10, 15, 20)g2.draw(easterEgg
)
77Specifying an Ellipse
78Lines and Points
- Line2D.Double segment new Line2D.Double(x1, x2,
y1, y2) - More object-oriented to use Point2D.Double for
the end pointsPoint2D.Double from new
Point2D.Double(x1, y1)Point2D.Double to new
Point2D.Double(x2, y2)Line2D.Double segment
new Line2D.Double(from, to) - Draw thick linesg2.setStroke(new
BasicStroke(4.0F)) // 4 pixels
79Colors
- Specify red, green, blue between 0.0F and
1.0FColor magenta new Color(1.0F, 0.0F, 1.0F) - Standard colorsColor.blackColor.yellowColor.pin
k. . . - Set color in graphics contextg2.setColor(Color.p
ink) - Then draw or fill shapesg2.fill(easterEgg)
80Text and Fonts
- Specify text and base pointg2.drawString("Applet
", 50, 100) - Font object has
- face name (Serif, SansSerif, Monospaced,
...) - style (Font.PLAIN, Font.BOLD, Font.ITALIC)
- point size (12 point normal size)
- g2.setFont(new Font("Serif", Font.BOLD, 36))
81Common Fonts
82Basepoint and Baseline
83Plan Complex Shapes with Graph Paper
84The Car Drawer Applet
85File CarApplet.java
- 1 import java.applet.Applet
- 2 import java.awt.Graphics
- 3 import java.awt.Graphics2D
- 4 import java.awt.Rectangle
- 5
- 6/
- 7 An applet that draws two rectangles.
- 8/
- 9 public class RectangleApplet extends Applet
- 10 Continue
86- 11 public void paint(Graphics g)
- 12
- 13 // recover Graphics2D
- 14
- 15 Graphics2D g2 (Graphics2D)g
- 16
- 17 // construct a rectangle and draw it
- 18
- 19 Rectangle cerealBox new Rectangle(5, 10,
20, 30) - 20 g2.draw(cerealBox)
- 21 Continue
87- 22 // move rectangle 15 units sideways and 25
units down - 23
- 24 cerealBox.translate(15, 25)
- 25
- 26 // draw moved rectangle
- 27
- 28 g2.draw(cerealBox)
- 29
- 30
88File Car.java
- 1 import java.awt.Graphics2D
- 2 import java.awt.geom.Ellipse2D
- 3 import java.awt.geom.Line2D
- 4 import java.awt.geom.Point2D
- 5 import java.awt.geom.Rectangle2D
- 6
- 7/
- 8 A car shape that can be positioned anywhere on
the screen. - 9/
- 10 public class Car
- 11 Continue
89- 12 /
- 13 Constructs a car with a given top left cor
ner - 14 _at_param x the x coordinate of the top left
corner - 15 _at_param y the y coordinate of the top left
corner - 16 /
- 17 public Car(double x, double y)
- 18
- 19 xLeft x
- 20 yTop y
- 21
- 22 Continue
90- 23 /
- 24 Draws the car
- 25 _at_param g2 the graphics context
- 26 /
- 27 public void draw(Graphics2D g2)
- 28
- 29 Rectangle2D.Double body
- 30 new Rectangle2D.Double(xLeft, yTop 10, 60
, 10) - 31 Ellipse2D.Double frontTire
- 32 new Ellipse2D.Double( xLeft 10,
yTop 20, 10, 10) - 33 Ellipse2D.Double rearTire
- 34 new Ellipse2D.Double(xLeft 40,
yTop 20, 10, 10)
91- 35
- 36 // the bottom of the front windshield
- 37 Point2D.Double r1
- 38 new Point2D.Double(xLeft 10, yTop
10) - 39 // the front of the roof
- 40 Point2D.Double r2
- 41 new Point2D.Double(xLeft 20, yTop)
- 42 // the rear of the roof
- 43 Point2D.Double r3
- 44 new Point2D.Double(xLeft 40, yTop)
- 45 // the bottom of the rear windshield
- 46 Point2D.Double r4
- 47 new Point2D.Double(xLeft 50, yTop
10) - 48
92- 49 Line2D.Double frontWindshield
- 50 new Line2D.Double(r1, r2)
- 51 Line2D.Double roofTop
- 52 new Line2D.Double(r2, r3)
- 53 Line2D.Double rearWindshield
- 54 new Line2D.Double(r3, r4)
- 55
- 56 g2.draw(body)
- 57 g2.draw(frontTire)
- 58 g2.draw(rearTire)
- 59 g2.draw(frontWindshield)
- 60 g2.draw(roofTop)
- 61 g2.draw(rearWindshield)
93- 62
- 63
- 64 private double xLeft
- 65 private double yTop
- 66
94Reading Text Input
- Call JOptionPane.showInputDialog in the
constructor - Dialog has warning label--security feature
- Set instance variables with the input results
- Read them in the paint method
- Need to wait for chapter 10/12 for more elegant
input
95Applet Dialog with Warning Label
96File ColorApplet.java
- 1import java.applet.Applet
- 2import java.awt.Color
- 3import java.awt.Graphics
- 4import java.awt.Graphics2D
- 5import java.awt.Rectangle
- 6import javax.swing.JOptionPane
- 7
- 8/
- 9 An applet that lets a user choose a color by s
pecifying - 10 the fractions of red, green, and blue.
- 11/
97- 12public class ColorApplet extends Applet
- 13
- 14 public ColorApplet()
- 15
- 16 String input
- 17
- 18 // ask the user for red, green, blue value
s - 19
- 20 input JOptionPane.showInputDialog("red"
) - 21 float red Float.parseFloat(input)
- 22
- 23 input JOptionPane.showInputDialog("green
") - 24 float green Float.parseFloat(input)
98- 25
- 26 input JOptionPane.showInputDialog("blue
") - 27 float blue Float.parseFloat(input)
- 28
- 29 fillColor new Color(red, green, blue)
- 30
- 31
- 32 public void paint(Graphics g)
- 33
- 34 Graphics2D g2 (Graphics2D)g
- 35
- 36 // select color into graphics context
- 37
- 38 g2.setColor(fillColor)
99- 39
- 40 // construct and fill a square whose cente
r is - 41 // the center of the window
- 42
- 43 Rectangle square new Rectangle(
- 44 (getWidth() - SQUARE_LENGTH) / 2,
- 45 (getHeight() - SQUARE_LENGTH) / 2,
- 46 SQUARE_LENGTH,
- 47 SQUARE_LENGTH)
- 48
- 49 g2.fill(square)
- 50
- 51
100- 52 private static final int SQUARE_LENGTH 100
- 53
- 54 private Color fillColor
- 55
- 56
101Comparing Visual and Numerical Information
- Compute intersection between circle and vertical
line - Circle has radius r 100 and center (a, b)
(100, 100) - Line has constant x value
- Intersection points are Plot circle, line,
computed intersection points - If the points are correct, then the visual and
numerical results are the same
102Intersection of a Line and a Circle
103File IntersectionApplet.java
- 1 import java.applet.Applet
- 2 import java.awt.Graphics
- 3 import java.awt.Graphics2D
- 4 import java.awt.geom.Ellipse2D
- 5 import java.awt.geom.Line2D
- 6 import javax.swing.JOptionPane
- 7
- 8 /
- 9 An applet that computes and draws the intersec
tion points - 10 of a circle and a line.
- 11 /
104- 12 public class IntersectionApplet extends Applet
- 13
- 14 public IntersectionApplet()
- 15
- 16 String input
- 17 JOptionPane.showInputDialog("x")
- 18 x Integer.parseInt(input)
- 19
- 20
- 21 public void paint(Graphics g)
- 22
- 23 Graphics2D g2 (Graphics2D)g
- 24
105- 25 double r 100 // the radius of the circl
e - 26
- 27 // draw the circle
- 28
- 29 Ellipse2D.Double circle
- 30 new Ellipse2D.Double(0, 0, 2 RADIUS
, 2 RADIUS) - 31 g2.draw(circle)
- 32
- 33 // draw the vertical line
- 34
- 35 Line2D.Double line
- 36 new Line2D.Double(x, 0, x, 2 RADIUS)
106- 37 g2.draw(line)
- 38
- 39 // compute the intersection points
- 40
- 41 double a RADIUS
- 42 double b RADIUS
- 43
- 44 double root Math.sqrt(RADIUS RADIUS -
(x - a) (x - a)) - 45 double y1 b root
- 46 double y2 b - root
- 47
- 48 // draw the intersection points
107- 49
- 50 LabeledPoint p1 new LabeledPoint(x, y1)
- 51 LabeledPoint p2 new LabeledPoint(x, y2)
- 52
- 53 p1.draw(g2)
- 54 p2.draw(g2)
- 55
- 56
- 57 private static final double RADIUS 100
- 58 private double x
- 59
108Coordinate Transformations
- Plot temperature data in Phoenix
- x ranges from 1 (January) to 12 (December)
- y ranges from 11 degrees (Celsius) to 33 degrees
- Transform user coordinates to pixel coordinates
- Encapsulate computation in convenience methods
xpixel, ypixel (see code) - Even better, use graphics context transforms
(advanced topic)
109Temperature Chart
110File ChartApplet.java
- 1 import java.applet.Applet
- 2 import java.awt.Graphics
- 3 import java.awt.Graphics2D
- 4 import java.awt.geom.Line2D
- 5
- 6 /
- 7 This applet draws a chart of the average monthly
- 8 temperatures in Phoenix, AZ.
- 9 /
- 10 public class ChartApplet extends Applet
- 11
111- 12 public void paint(Graphics g)
- 13
- 14 Graphics2D g2 (Graphics2D)g
- 15
- 16 month 1
- 17
- 18 drawBar(g2, JAN_TEMP)
- 19 drawBar(g2, FEB_TEMP)
- 20 drawBar(g2, MAR_TEMP)
- 21 drawBar(g2, APR_TEMP)
- 22 drawBar(g2, MAY_TEMP)
- 23 drawBar(g2, JUN_TEMP)
- 24 drawBar(g2, JUL_TEMP)
- 25 drawBar(g2, AUG_TEMP)
112- 26 drawBar(g2, SEP_TEMP)
- 27 drawBar(g2, OCT_TEMP)
- 28 drawBar(g2, NOV_TEMP)
- 29 drawBar(g2, DEC_TEMP)
- 30
- 31
- 32 /
- 33 Draws a bar for the current month and increment
s - 34 the month.
- 35 _at_param g2 the graphics context
- 36 _at_param temperature the temperature for the
- month
- 37 /
113- 38 public void drawBar(Graphics2D g2, int temper
ature) - 39
- 40 Line2D.Double bar
- 41 new Line2D.Double(xpixel(month), ypix
el(0), - 42 xpixel(month), ypixel(temperature))
- 43
- 44 g2.draw(bar)
- 45
- 46 month
- 47
- 48
114- 49 /
- 50 Converts from user coordinates to pixel co
ordinates - 51 _at_param xuser an x-value in user coordinate
s - 52 _at_return the corresponding value in pixel coo
rdinates - 53 /
- 54 public double xpixel(double xuser)
- 55
- 56 return (xuser - XMIN) (getWidth() - 1) /
(XMAX - XMIN) - 57
- 58
115- 59 /
- 60 Converts from user coordinates to pixel co
ordinates - 61 _at_param yuser a y-value in user coordinates
- 62 _at_return the corresponding value in pixel c
oordinates - 63 /
- 64 public double ypixel(double yuser)
- 65
- 66 return (yuser - YMAX) (getHeight() - 1)
/ (YMIN - YMAX) - 67
- 68
116- 69 private static final int JAN_TEMP 11
- 70 private static final int FEB_TEMP 13
- 71 private static final int MAR_TEMP 16
- 72 private static final int APR_TEMP 20
- 73 private static final int MAY_TEMP 25
- 74 private static final int JUN_TEMP 31
- 75 private static final int JUL_TEMP 33
- 76 private static final int AUG_TEMP 32
- 77 private static final int SEP_TEMP 29
- 78 private static final int OCT_TEMP 23
- 79 private static final int NOV_TEMP 16
- 80 private static final int DEC_TEMP 12
117- 81
- 82 private static final double XMIN 1
- 83 private static final double XMAX 12
- 84 private static final double YMIN 0
- 85 private static final double YMAX 40
- 86
- 87 private int month
- 88
- 89
- 90