Download Slide 1

Document related concepts
no text concepts found
Transcript
Programming Fundamentals I (COSC1336),
Lecture 9 (prepared after Chapter 8 of
Liang’s 2011 textbook)
Stefan Andrei
5/24/2017
COSC-1336, Lecture 9
1
Overview of Previous Lecture




To give examples of representing data using twodimensional arrays (§7.1).
To declare variables for two-dimensional arrays,
create arrays, and access array elements in a twodimensional array using row and column indexes
(§7.2).
To program common operations for two-dimensional
arrays (displaying arrays, summing all elements,
finding min and max elements, and random shuffling)
(§7.3).
To pass two-dimensional arrays to methods (§7.4).
5/24/2017
COSC-1336, Lecture 9
2
Overview of Previous Lecture (cont)




To write a program for grading multiple-choice
questions using two-dimensional arrays (§7.5).
To solve the closest-pair problem using twodimensional arrays (§7.6).
To check a Sudoku solution using two-dimensional
arrays (§7.7).
To use multidimensional arrays (§7.8).
5/24/2017
COSC-1336, Lecture 9
3
Motivation of the current lecture
After learning the preceding chapters, you are
capable of solving many programming problems
using selections, loops, methods, and arrays.
 However, these Java features are not sufficient
for developing graphical user interfaces and large
scale software systems.
 Suppose you want to develop a graphical user
interface as shown below.
 How do you program it?

5/24/2017
COSC-1336, Lecture 9
4
Overview of This Lecture








To describe objects and classes, and use classes to
model objects (§8.2).
To use UML graphical notations to describe classes and
objects (§8.2).
To demonstrate defining classes and creating objects
(§8.3).
To create objects using constructors (§8.4).
To access objects via object reference variables (§8.5).
To define a reference variable using a reference type
(§8.5.1).
To access an object’s data and methods using the
object member access operator (.) (§8.5.2).
To define data fields of reference types and assign
default values for an object’s data fields (§8.5.3).
5/24/2017
COSC-1336, Lecture 9
5
Overview of This Lecture (cont.)







To distinguish between object reference variables and
primitive data type variables (§8.5.4).
To use classes Date, Random, and JFrame in the Java
library (§8.6).
To distinguish between instance and static variables
and methods (§8.7).
To define private data fields with appropriate get and
set methods (§8.8).
To encapsulate data fields to make classes easy to
maintain (§8.9).
To develop methods with object arguments and
differentiate between primitive-type arguments and
object-type arguments (§8.10).
To store and process objects in arrays (§8.11).
5/24/2017
COSC-1336, Lecture 9
6
Object-Oriented Programming Concepts
 Object-oriented programming (OOP) involves
programming using objects.
 An object represents an entity in the real world that
can be distinctly identified.
 For example, a student, a desk, a circle, a button,
and even a loan can all be viewed as objects.
 An object has a unique identity, state, and behaviors.
 The state of an object consists of a set of data fields
(also known as properties) with their current values.
 The behavior of an object is defined by a set of
methods.
5/24/2017
COSC-1336, Lecture 9
7
Difference between traditional and
object-oriented approaches

Suppose you have a fruit basket with apples,
peaches, and pineapples:


Conventional approach: one large basket with
all fruits and one drawer with two knives.
Object-oriented approach: three smaller
baskets:



5/24/2017
one with apples and their knife,
another with peaches with no knife, and
the last one with pineapples and the larger knife.
COSC-1336, Lecture 9
8
Traditional approach → Java
public class FruitBasket {
static String nameOfFruit = “”;
static int typeKnife = 0;
public static void main(String args[]) {
nameOfFruit = “apple”;
typeKnife = 1;
System.out.println(“We eat “ + nameOfFruit +
“ with “ + typeKnife);
nameOfFruit = “Pineapple”;
typeKnife = 2;
System.out.println(“We eat “ + nameOfFruit +
“ with “ + typeKnife);
// ... The operations ...
}
}
5/24/2017
COSC-1336, Lecture 9
9
Object-oriented approach → Java
class Fruit {
String nameOfFruit;
int typeKnife;
Fruit(String nF, int tK) {
nameOfFruit = nF; typeKnife = tK;
}
// ... The operations ...
}
public class FruitBasket {
public static void main(String args[]) {
Fruit obj1 = new Fruit(“apple”, 1);
System.out.println(“We eat “ + obj1);
Fruit obj2 = new Fruit(“pineapple”, 2);
System.out.println(“We eat “ + obj2);
}
}
5/24/2017
COSC-1336, Lecture 9
10
Difference between traditional and
object-oriented approaches (cont)

Another example: manual gear versus
automatic gear vehicle:


5/24/2017
Conventional approach: manual gear, hence the
responsibility of changing the gear belongs to the
driver.
Object-oriented approach: automatic gear, hence
the operation of changing the gear while driving is
embedded into the car specification. The driver
does not need to change any gear, until stop!
COSC-1336, Lecture 9
11
Objects
A class template
Class Name: Circle
Data Fields:
radius is _______
Methods:
getArea
Circle Object 1
Circle Object 2
Circle Object 3
Data Fields:
radius is 10
Data Fields:
radius is 25
Data Fields:
radius is 125
Three objects of
the Circle class
 An object has both a state and behavior.
 The state (the values of the attributes) defines the
object, and the behavior defines what the object does.
5/24/2017
COSC-1336, Lecture 9
12
Classes
 Classes are constructs that define objects of
the same type.
 A Java class uses variables to define data fields
and methods to define behaviors.
 Additionally, a class provides a special type of
methods, known as constructors, which are
invoked to construct objects from the class.
5/24/2017
COSC-1336, Lecture 9
13
Classes
class Circle {
/** The radius of this circle */
double radius = 1.0;
/** Construct a circle object */
Circle() {
}
Data field
Constructors
/** Construct a circle object */
Circle(double newRadius) {
radius = newRadius;
}
/** Return the area of this circle */
double getArea() {
return radius * radius * 3.14159;
}
Method
}
5/24/2017
COSC-1336, Lecture 9
14
Unified Modeling Language (UML)
Class Diagram
Circle
UML Class Diagram
Class name
radius: double
Data fields
Circle()
Constructors and
methods
Circle(newRadius: double)
getArea(): double
circle1: Circle
radius = 1.0
5/24/2017
circle2: Circle
circle3: Circle
UML notation
for objects
radius = 125
radius = 25
COSC-1336, Lecture 9
15
Example: Defining Classes and
Creating Objects

Objective: Demonstrate creating objects,
accessing data, and using methods.
// Define the circle class with two constructors
class Circle1 {
double radius;
/** Construct a circle with radius 1 */
Circle1() { radius = 1.0; }
/** Construct a circle with a specified radius */
Circle1(double newRadius) { radius = newRadius; }
/** Return the area of this circle */
double getArea() { return radius * radius * Math.PI; }
}
5/24/2017
COSC-1336, Lecture 9
16
TestCircle1.java
public class TestCircle1 {
public static void main(String[] args) {
// Create a circle with radius 5.0
Circle1 myCircle = new Circle1(5.0);
System.out.println("The area of the circle of radius "
+ myCircle.radius + " is " + myCircle.getArea());
// Create a circle with radius 1
Circle1 yourCircle = new Circle1();
System.out.println("The area of the circle of radius "
+ yourCircle.radius + " is " + yourCircle.getArea());
// Modify circle radius
yourCircle.radius = 100;
System.out.println("The area of the circle of radius "
+ yourCircle.radius + " is " + yourCircle.getArea());
}
}
5/24/2017
COSC-1336, Lecture 9
17
Running TestCircle1.java
5/24/2017
COSC-1336, Lecture 9
18
Constructors
 Constructors are a special
Circle() {
}
kind of methods that are
invoked to construct objects.
Circle(double newRadius) {
radius = newRadius;
}
5/24/2017
COSC-1336, Lecture 9
19
Constructors (cont.)
 A constructor with no parameters is referred to
as a no-arg constructor.
 Constructors must have the same name as the
class itself.
 Constructors do not have a return type, not
even void.
 Constructors are invoked using the new operator
when an object is created.
 Constructors play the role of initializing objects.
5/24/2017
COSC-1336, Lecture 9
20
Creating Objects Using Constructors

General syntax:
new ClassName();

Examples:
new Circle();
new Circle(5.0);
5/24/2017
COSC-1336, Lecture 9
21
Default Constructor
 A class may be declared without constructors.
 In this case, a no-arg constructor with an empty
body is implicitly declared in the class (by JVM).
 This constructor, called a default constructor, is
provided automatically only if no constructors are
explicitly declared in the class.
5/24/2017
COSC-1336, Lecture 9
22
Declaring Object Reference Variables
To reference an object, assign the object to a
reference variable.
 To declare a reference variable, use the syntax:

ClassName objectRefVar;

Example:
Circle myCircle;
5/24/2017
COSC-1336, Lecture 9
23
Declaring and Creating Objects in a
Single Step

General syntax:
ClassName objectRefVar = new ClassName();
Assign object reference

Create an object
Example:
Circle myCircle = new Circle();
5/24/2017
COSC-1336, Lecture 9
24
Accessing Objects

Referencing the object’s data:
objectRefVar.data
e.g., myCircle.radius

Invoking the object’s method:
objectRefVar.methodName(arguments)
e.g., myCircle.getArea()
5/24/2017
COSC-1336, Lecture 9
25
animation
Trace Code
Declare myCircle
Circle myCircle = new Circle(5.0);
myCircle
no value
Circle yourCircle = new Circle();
yourCircle.radius = 100;
5/24/2017
COSC-1336, Lecture 9
26
animation
Trace Code (cont.)
Circle myCircle =
new Circle(5.0);
myCircle
no value
Circle yourCircle = new Circle();
yourCircle.radius = 100;
: Circle
radius: 5.0
Create a Circle
5/24/2017
COSC-1336, Lecture 9
27
animation
Trace Code (cont.)
Circle myCircle = new Circle(5.0);
myCircle
reference value
Circle yourCircle = new Circle();
yourCircle.radius = 100;
: Circle
Assign object reference
to myCircle
5/24/2017
COSC-1336, Lecture 9
radius: 5.0
28
animation
Trace Code (cont.)
myCircle
reference value
Circle myCircle = new Circle(5.0);
Circle yourCircle = new Circle();
: Circle
yourCircle.radius = 100;
radius: 5.0
yourCircle
no value
Declare yourCircle
5/24/2017
COSC-1336, Lecture 9
29
animation
Trace Code (cont.)
myCircle reference value
Circle myCircle = new Circle(5.0);
Circle yourCircle = new Circle();
yourCircle.radius = 100;
: Circle
radius: 5.0
yourCircle
no value
: Circle
Create a new
Circle object
5/24/2017
COSC-1336, Lecture 9
radius: 0.0
30
animation
Trace Code (cont.)
myCircle
reference value
Circle myCircle = new Circle(5.0);
Circle yourCircle = new Circle();
yourCircle.radius = 100;
: Circle
radius: 5.0
yourCircle reference value
Assign object
reference to
yourCircle
: Circle
radius: 1.0
5/24/2017
COSC-1336, Lecture 9
31
animation
Trace Code (cont.)
myCircle
reference value
Circle myCircle = new Circle(5.0);
Circle yourCircle = new Circle();
yourCircle.radius = 100;
: Circle
radius: 5.0
yourCircle reference value
: Circle
Change radius in
yourCircle
5/24/2017
COSC-1336, Lecture 9
radius: 100.0
32
Caution

Recall that you use
Math.methodName(arguments) (e.g., Math.pow(3, 2.5))
to invoke a method in the Math class.
 Can you invoke getArea() using Circle1.getArea()?
 The answer is no.
 All the methods used before this chapter are static
methods, which are defined using the static keyword.
 However, getArea() is non-static.
 It must be invoked from an object using

objectRefVar.methodName(arguments) (e.g.,
myCircle.getArea()).
More explanations will be given in the section on “Static
Variables, Constants, and Methods.”

5/24/2017
COSC-1336, Lecture 9
33
Reference Data Fields
The data fields can be of reference types.
 For example, the following Student class contains
a data field name of the String type.

public class Student {
// name has default value null
String name;
// age has default value 0
int age;
// isScienceMajor has default value false
boolean isScienceMajor;
// c has default value '\u0000'
char gender;
}
5/24/2017
COSC-1336, Lecture 9
34
The null Value
If a data field of a reference type does not
reference any object, the data field holds a
special literal value, null.

5/24/2017
COSC-1336, Lecture 9
35
Default Value for a Data Field
The default value of a data field is null for a
reference type, 0 for a numeric type, false for a
boolean type, and '\u0000' for a char type.

public class Test {
public static void main(String[] args) {
Student student = new Student();
System.out.println("name? " + student.name);
System.out.println("age? " + student.age);
System.out.println("isScienceMajor? " + student.isScienceMajor);
System.out.println("gender? " + student.gender);
}
}
5/24/2017
COSC-1336, Lecture 9
36
Example
 However, Java assigns no default value to a
local variable inside a method.
public class Test {
public static void main(String[] args) {
int x; // x has no default value
String y; // y has no default value
System.out.println("x is " + x);
System.out.println("y is " + y);
}
}
Compilation error: variables not initialized
5/24/2017
COSC-1336, Lecture 9
37
Differences between Variables of
Primitive Data Types and Object Types
Created using new Circle()
Primitive type
int i = 1
i
1
Object type
Circle c
c
reference
c: Circle
radius = 1
5/24/2017
COSC-1336, Lecture 9
38
Copying Variables of Primitive Data
Types and Object Types
Primitive type assignment i = j
Before:
After:
i
1
i
2
j
2
j
2
Object type assignment c1 = c2
Before:
5/24/2017
After:
c1
c1
c2
c2
c1: Circle
C2: Circle
c1: Circle
C2: Circle
radius = 5
radius = 9
radius = 5
radius = 9
COSC-1336, Lecture 9
39
Garbage Collection
As shown in the previous figure, after the
assignment statement c1 = c2, c1 points to the
same object referenced by c2.
 The object previously referenced by c1 is no
longer referenced.
 This object is known as garbage.
 The garbage is automatically collected by
Java Virtual Machine (JVM).

5/24/2017
COSC-1336, Lecture 9
40
Garbage Collection (cont.)


TIP: If you know that an object is no longer
needed, you can explicitly assign null to a
reference variable for the object.
The JVM will automatically collect the space if
the object is not referenced by any variable.
5/24/2017
COSC-1336, Lecture 9
41
The Date Class
Java provides a system-independent encapsulation of
date and time in the java.util.Date class.
 You can use the Date class to create an instance for
the current date and time and use its toString()
method to return the date and time as a String.

The + sign indicates
public modifer
5/24/2017
java.util.Date
+Date()
Constructs a Date object for the current time.
+Date(elapseTime: long)
Constructs a Date object for a given time in
milliseconds elapsed since January 1, 1970, GMT.
+toString(): String
Returns a string representing the date and time.
+getTime(): long
Returns the number of milliseconds since January 1,
1970, GMT.
+setTime(elapseTime: long): void
Sets a new elapse time in the object.
COSC-1336, Lecture 9
42
The Date Class Example

For example, the following code:
java.util.Date date = new java.util.Date();
System.out.println(date.toString());
displays a string like Fri Mar 11 13:50:19
GMT 2011.

5/24/2017
COSC-1336, Lecture 9
43
The Random Class
You have used Math.random() to obtain a random
double value between 0.0 and 1.0 (excluding 1.0).
 A more useful random number generator is provided
in the java.util.Random class.

java.util.Random
+Random()
Constructs a Random object with the current time as its seed.
+Random(seed: long)
Constructs a Random object with a specified seed.
+nextInt(): int
Returns a random int value.
+nextInt(n: int): int
Returns a random int value between 0 and n (exclusive).
+nextLong(): long
Returns a random long value.
+nextDouble(): double
Returns a random double value between 0.0 and 1.0 (exclusive).
+nextFloat(): float
Returns a random float value between 0.0F and 1.0F (exclusive).
+nextBoolean(): boolean
Returns a random boolean value.
5/24/2017
COSC-1336, Lecture 9
44
The Random Class Example
If two Random objects have the same seed, they will
generate identical sequences of numbers.
 For example, the following code creates two Random
objects with the same seed 3.

Random random1 = new Random(3);
System.out.print("From random1: ");
for (int i = 0; i < 10; i++)
System.out.print(random1.nextInt(1000) + " ");
Random random2 = new Random(3);
System.out.print("\nFrom random2: ");
for (int i = 0; i < 10; i++)
System.out.print(random2.nextInt(1000) + " ");
From random1: 734 660 210 581 128 202 549 564 459 961
From random2: 734 660 210 581 128 202 549 564 459 961
5/24/2017
COSC-1336, Lecture 9
45
Displaying GUI Components
When you develop programs to create
graphical user interfaces, you will use Java
classes such as JFrame, JButton,
JRadioButton, JComboBox, and JList to create
frames, buttons, radio buttons, combo boxes,
lists, and so on.
 Here is an example that creates two
windows using the JFrame class.

5/24/2017
COSC-1336, Lecture 9
46
TestFrame.java
import javax.swing.JFrame;
public class TestFrame {
public static void main(String[] args) {
JFrame frame1 = new JFrame();
frame1.setTitle("Window 1");
frame1.setSize(200, 150);
frame1.setLocation(200, 100);
frame1.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame1.setVisible(true);
JFrame frame2 = new JFrame();
frame2.setTitle("Window 2");
frame2.setSize(200, 150);
frame2.setLocation(410, 100);
frame2.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame2.setVisible(true);
}
}
5/24/2017
COSC-1336, Lecture 9
47
Running TestFrame.java
5/24/2017
COSC-1336, Lecture 9
48
animation
Trace Code
JFrame frame1 = new JFrame(); frame1 reference
frame1.setTitle("Window 1");
frame1.setSize(200, 150);
: JFrame
frame1.setVisible(true);
title:
JFrame frame2 = new JFrame();
width:
frame2.setTitle("Window 2");
height:
frame2.setSize(200, 150);
visible:
frame2.setVisible(true);
5/24/2017
COSC-1336, Lecture 9
Declare, create,
and assign in
one statement
49
animation
Trace Code
JFrame frame1 = new JFrame(); frame1 reference
frame1.setTitle("Window 1");
frame1.setSize(200, 150);
: JFrame
frame1.setVisible(true);
title: "Window 1"
JFrame frame2 = new JFrame();
width:
frame2.setTitle("Window 2");
height:
frame2.setSize(200, 150);
visible:
frame2.setVisible(true);
5/24/2017
COSC-1336, Lecture 9
Set title property
50
animation
Trace Code
JFrame frame1 = new JFrame(); frame1 reference
frame1.setTitle("Window 1");
frame1.setSize(200, 150);
: JFrame
frame1.setVisible(true);
title: "Window 1"
JFrame frame2 = new JFrame();
width: 200
frame2.setTitle("Window 2");
height: 150
frame2.setSize(200, 150);
visible:
frame2.setVisible(true);
5/24/2017
COSC-1336, Lecture 9
Set size property
51
animation
Trace Code
JFrame frame1 = new JFrame(); frame1 reference
frame1.setTitle("Window 1");
frame1.setSize(200, 150);
: JFrame
frame1.setVisible(true);
title: "Window 1"
JFrame frame2 = new JFrame();
width: 200
frame2.setTitle("Window 2");
height: 150
frame2.setSize(200, 150);
visible: true
frame2.setVisible(true);
5/24/2017
COSC-1336, Lecture 9
Set visible
property
52
animation
Trace Code
JFrame frame1 = new JFrame(); frame1 reference
frame1.setTitle("Window 1");
frame1.setSize(200, 150);
: JFrame
frame1.setVisible(true);
title: "Window 1"
JFrame frame2 = new JFrame();
width: 200
frame2.setTitle("Window 2");
height: 150
frame2.setSize(200, 150);
visible: true
frame2.setVisible(true);
frame2 reference
Declare, create,
and assign in
one statement
: JFrame
title:
width:
height:
visible:
5/24/2017
COSC-1336, Lecture 9
53
animation
Trace Code
JFrame frame1 = new JFrame(); frame1 reference
frame1.setTitle("Window 1");
frame1.setSize(200, 150);
: JFrame
frame1.setVisible(true);
title: "Window 1"
JFrame frame2 = new JFrame();
width: 200
frame2.setTitle("Window 2");
height: 150
visible: true
frame2.setSize(200, 150);
frame2.setVisible(true);
frame2 reference
Set title
property
: JFrame
title: "Window 2"
width:
height:
visible:
5/24/2017
COSC-1336, Lecture 9
54
animation
Trace Code
JFrame frame1 = new JFrame(); frame1 reference
frame1.setTitle("Window 1");
frame1.setSize(200, 150);
: JFrame
frame1.setVisible(true);
title: "Window 1"
JFrame frame2 = new JFrame();
width: 200
frame2.setTitle("Window 2");
height: 150
frame2.setSize(200, 150);
visible: true
frame2.setVisible(true);
frame2 reference
Set size
property
: JFrame
title: "Window 2"
width: 200
height: 150
visible:
5/24/2017
COSC-1336, Lecture 9
55
animation
Trace Code
JFrame frame1 = new JFrame(); frame1 reference
frame1.setTitle("Window 1");
frame1.setSize(200, 150);
: JFrame
frame1.setVisible(true);
title: "Window 1"
JFrame frame2 = new JFrame();
width: 200
frame2.setTitle("Window 2");
height: 150
frame2.setSize(200, 150);
visible: true
frame2.setVisible(true);
frame2 reference
: JFrame
title: "Window 2"
width: 200
height: 150
visible: true
5/24/2017
COSC-1336, Lecture 9
Set visible
property
56
Adding GUI Components to Window
You can add graphical user interface
components, such as buttons, labels, text fields,
combo boxes, lists, and menus, to the window.
 The components are defined using classes.
 Here is an example to create buttons, labels,
text fields, check boxes, radio buttons, and
combo boxes.

5/24/2017
COSC-1336, Lecture 9
57
GUIComponents.java
import javax.swing.*;
public class GUIComponents {
public static void main(String[] args) {
// Create a button with text OK
JButton jbtOK = new JButton("OK");
// Create a button with text Cancel
JButton jbtCancel = new JButton("Cancel");
// Create a label with text "Enter your name: "
JLabel jlblName = new JLabel("Enter your name: ");
// Create a text field with text "Type Name Here"
JTextField jtfName = new JTextField("Type Name Here");
// Create a check box with text bold
JCheckBox jchkBold = new JCheckBox("Bold");
5/24/2017
COSC-1336, Lecture 9
58
GUIComponents.java (cont)
// Create a check box with text italic
JCheckBox jchkItalic = new JCheckBox("Italic");
// Create a radio button with text red
JRadioButton jrbRed = new JRadioButton("Red");
// Create a radio button with text yellow
JRadioButton jrbYellow = new JRadioButton("Yellow");
// Create a combo box with several choices
JComboBox jcboColor = new JComboBox(new String[]
{"Freshman", "Sophomore", "Junior", "Senior"});
// Create a panel to group components
JPanel panel = new JPanel();
panel.add(jbtOK);
// Add the OK button to the panel
panel.add(jbtCancel);
5/24/2017
COSC-1336, Lecture 9
59
GUIComponents.java (cont)
// Add the Cancel button to the panel
panel.add(jlblName);
// Add the label to the panel
panel.add(jtfName);
// Add the text field to the panel
panel.add(jchkBold);
// Add the check box to the panel
panel.add(jchkItalic);
// Add the check box to the panel
panel.add(jrbRed);
// Add the radio button to the panel
panel.add(jrbYellow);
// Add the radio button to the panel
panel.add(jcboColor);
5/24/2017
COSC-1336, Lecture 9
60
GUIComponents.java (cont)
// Add the combo box to the panel
JFrame frame = new JFrame();
// Create a frame
frame.add(panel);
// Add the panel to the frame
frame.setTitle("Show GUI Components");
frame.setSize(450, 100);
frame.setLocation(200, 100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}
5/24/2017
COSC-1336, Lecture 9
61
Running GUIComponents.java
5/24/2017
COSC-1336, Lecture 9
62
Instance Variables, and Methods
 Instance variables belong to a specific
instance.
 Instance methods are invoked by an instance
of the class.
5/24/2017
COSC-1336, Lecture 9
63
Static Variables, Constants, and Methods
 Static variables are shared by all the instances
of the class.
 Static methods are not tied to a specific object.
 Static constants are final variables shared by
all the instances of the class.
 To declare static variables, constants, and
methods, use the static modifier.
5/24/2017
COSC-1336, Lecture 9
64
Static Variables, Constants, and
Methods (cont.)
instantiate
circle1
radius = 1
numberOfObjects = 2
Circle
Memory
1
radius: double
numberOfObjects: int
getNumberOfObjects(): int
+getArea(): double
UML Notation:
+: public variables or methods
underline: static variables or methods
5/24/2017
instantiate
radius
2
numberOfObjects
5
radius
After two Circle
objects were created,
numberOfObjects
is 2.
circle2
radius = 5
numberOfObjects = 2
COSC-1336, Lecture 9
65
Example of Using Instance and Class
Variables and Method


Objective: Demonstrate the roles of instance
and class variables and their uses.
This example adds a class variable
numberOfObjects to track the number of
Circle objects created.
5/24/2017
COSC-1336, Lecture 9
66
The Circle2.java class
public class Circle2 {
/** The radius of the circle */
double radius;
/** The number of the objects created */
static int numberOfObjects = 0;
/** Construct a circle with radius 1 */
Circle2() {
radius = 1.0;
numberOfObjects++;
}
5/24/2017
COSC-1336, Lecture 9
67
The Circle2.java class (cont.)
/** Construct a circle with a specified radius */
Circle2(double newRadius) {
radius = newRadius;
numberOfObjects++;
}
/** Return numberOfObjects */
static int getNumberOfObjects() {
return numberOfObjects;
}
/** Return the area of this circle */
double getArea() {
return radius * radius * Math.PI;
}
}
5/24/2017
COSC-1336, Lecture 9
68
Visibility Modifiers and Accessor/
Mutator Methods
By default, the class, variable, or method can be
accessed by any class in the same package.


public
 The class, data, or method is visible to any class in
any package.

private
 The data or methods can be accessed only by the
declaring class.
 The get() and set() methods are used to read and
modify private data.
5/24/2017
COSC-1336, Lecture 9
69
package p1;
public class C1 {
public int x;
int y;
private int z;
public void m1() {
}
void m2() {
}
private void m3() {
}
}
package p2;
public class C2 {
void aMethod() {
C1 o = new C1();
can access o.x;
can access o.y;
cannot access o.z;
can invoke o.m1();
can invoke o.m2();
cannot invoke o.m3();
can invoke o.m1();
cannot invoke o.m2();
cannot invoke o.m3();
}
}
}
}
package p1;
class C1 {
...
}
public class C3 {
void aMethod() {
C1 o = new C1();
can access o.x;
cannot access o.y;
cannot access o.z;
package p2;
public class C2 {
can access C1
}
public class C3 {
cannot access C1;
can access C2;
}
 The private modifier restricts access to within a class, the
default modifier restricts access to within a package, and the
public modifier enables unrestricted access.
5/24/2017
COSC-1336, Lecture 9
70
Note
An object cannot access its private members, as shown
in (b). It is OK, however, if the object is declared in its
own class, as shown in (a).
public class Foo {
private boolean x;
public static void main(String[] args) {
Foo foo = new Foo();
System.out.println(foo.x);
System.out.println(foo.convert());
}
public class Test {
public static void main(String[] args) {
Foo foo = new Foo();
System.out.println(foo.x);
System.out.println(foo.convert(foo.x));
}
}
private int convert(boolean b) {
return x ? 1 : -1;
}
}
(a) This is OK because object foo is used inside the Foo class
5/24/2017
(b) This is wrong because x and convert are private in Foo.
COSC-1336, Lecture 9
71
Why Data Fields Should Be private?
 To protect data.
 To make class easy to maintain.
5/24/2017
COSC-1336, Lecture 9
72
Example of Data Field Encapsulation.
The UML class icon for Circle
Circle
The - sign indicates
private modifier
5/24/2017
-radius: double
The radius of this circle (default: 1.0).
-numberOfObjects: int
The number of circle objects created.
+Circle()
Constructs a default circle object.
+Circle(radius: double)
Constructs a circle object with the specified radius.
+getRadius(): double
Returns the radius of this circle.
+setRadius(radius: double): void
Sets a new radius for this circle.
+getNumberOfObject(): int
Returns the number of circle objects created.
+getArea(): double
Returns the area of this circle.
COSC-1336, Lecture 9
73
Circle3.java
public class Circle3 {
/** The radius of the circle */
private double radius = 1;
/** The number of the objects created */
private static int numberOfObjects = 0;
/** Construct a circle with radius 1 */
public Circle3() { numberOfObjects++; }
/** Construct a circle with a specified radius */
public Circle3(double newRadius) {
radius = newRadius;
numberOfObjects++;
}
5/24/2017
COSC-1336, Lecture 9
74
Circle3.java
(cont.)
/** Return radius */
public double getRadius() { return radius; }
/** Set a new radius */
public void setRadius(double newRadius) {
radius = (newRadius >= 0) ? newRadius : 0; }
/** Return numberOfObjects */
public static int getNumberOfObjects() {
return numberOfObjects; }
/** Return the area of this circle */
public double getArea() {
return radius * radius * Math.PI;
}
}
5/24/2017
COSC-1336, Lecture 9
75
TestCircle3.java
public class TestCircle3 {
public static void main(String[] args) {
// Create a Circle with radius 5.0
Circle3 myCircle = new Circle3(5.0);
System.out.println("The area of the circle of
radius " + myCircle.getRadius() + " is " +
myCircle.getArea());
// Increase myCircle's radius by 10%
myCircle.setRadius(myCircle.getRadius() * 1.1);
System.out.println("The area of the circle of
radius " + myCircle.getRadius() + " is " +
myCircle.getArea());
}
}
5/24/2017
COSC-1336, Lecture 9
76
Running TestCircle3.java
5/24/2017
COSC-1336, Lecture 9
77
Passing Objects to Methods

Passing by value for primitive type value (the
value is passed to the parameter)

Passing by value for reference type value
(the value is the reference to the object)
5/24/2017
COSC-1336, Lecture 9
78
TestPassObject.java
public class TestPassObject {
public static void main(String[] args) {
// Create a Circle object with radius 1
Circle3 myCircle = new Circle3(1);
// Print areas for radius 1, 2, 3, 4, and 5.
int n = 5;
printAreas(myCircle, n);
// See myCircle.radius and times
System.out.println("\n" + "Radius is " +
myCircle.getRadius());
System.out.println("n is " + n);
}
5/24/2017
COSC-1336, Lecture 9
79
TestPassObject.java
(cont.)
/** Print a table of areas for radius */
public static void printAreas(Circle3 c, int times) {
System.out.println("Radius \t\tArea");
while (times >= 1) {
System.out.println(c.getRadius() + "\t\t" +c.getArea());
c.setRadius(c.getRadius() + 1);
times--;
}
}
}
5/24/2017
COSC-1336, Lecture 9
80
Running TestPassObject.java
5/24/2017
COSC-1336, Lecture 9
81
Passing Objects to Methods (cont.)
Stack
Space required for the
printAreas method
int times: 5
Circle c: reference
Pass by value (here
the value is 5)
Pass by value
(here the value is
the reference for
the object)
Space required for the
main method
int n: 5
myCircle: reference
5/24/2017
Heap
A circle
object
COSC-1336, Lecture 9
82
Array of Objects
Circle[] circleArray = new Circle[10];

An array of objects is actually an array of
reference variables.
 So invoking circleArray[1].getArea() involves
two levels of referencing as shown in the next
figure.
 circleArray references to the entire array.
 circleArray[1] references to a Circle object.
5/24/2017
COSC-1336, Lecture 9
83
Array of Objects (cont.)
Circle[] circleArray = new Circle[10];
circleArray
5/24/2017
reference
circleArray[0]
circleArray[1]
Circle object 0
…
Circle object 1
circleArray[9]
Circle object 9
COSC-1336, Lecture 9
84
Array of Objects (cont.)

Summarizing the areas of the circles.
public class TotalArea {
public static void main(String[] args) {
// Declare circleArray
Circle3[] circleArray;
// Create circleArray
circleArray = createCircleArray();
// Print circleArray and total areas of the circles
printCircleArray(circleArray);
}
5/24/2017
COSC-1336, Lecture 9
85
TotalArea.java
(cont.)
/** Create an array of Circle objects */
public static Circle3[] createCircleArray() {
Circle3[] circleArray = new Circle3[5];
for (int i = 0; i < circleArray.length; i++) {
circleArray[i] = new Circle3(Math.random() * 100);
}
return circleArray;
}
5/24/2017
COSC-1336, Lecture 9
86
TotalArea.java
(cont.)
/** Print an array of circles and their total area */
public static void printCircleArray(Circle3[]
circleArray) {
System.out.printf("%-30s%-15s\n", "Radius", "Area");
for (int i = 0; i < circleArray.length; i++) {
System.out.printf("%-30f%-15f\n",
circleArray[i].getRadius(),
circleArray[i].getArea());
}
System.out.println("------------------------------");
System.out.printf("%-30s%-15f\n", "The total areas of
circles is", sum(circleArray));
}
5/24/2017
COSC-1336, Lecture 9
87
TotalArea.java
(cont.)
/** Add circle areas */
public static double sum(Circle3[] circleArray) {
// Initialize sum
double sum = 0;
// Add areas to sum
for (int i = 0; i < circleArray.length; i++)
sum += circleArray[i].getArea();
return sum;
}
} // from TotalArea class
5/24/2017
COSC-1336, Lecture 9
88
Running TotalArea.java
5/24/2017
COSC-1336, Lecture 9
89
Summary








To describe objects and classes, and use classes to
model objects (§8.2).
To use UML graphical notations to describe classes and
objects (§8.2).
To demonstrate defining classes and creating objects
(§8.3).
To create objects using constructors (§8.4).
To access objects via object reference variables (§8.5).
To define a reference variable using a reference type
(§8.5.1).
To access an object’s data and methods using the
object member access operator (.) (§8.5.2).
To define data fields of reference types and assign
default values for an object’s data fields (§8.5.3).
5/24/2017
COSC-1336, Lecture 9
90
Summary (cont.)







To distinguish between object reference variables and
primitive data type variables (§8.5.4).
To use classes Date, Random, and JFrame in the Java
library (§8.6).
To distinguish between instance and static variables
and methods (§8.7).
To define private data fields with appropriate get and
set methods (§8.8).
To encapsulate data fields to make classes easy to
maintain (§8.9).
To develop methods with object arguments and
differentiate between primitive-type arguments and
object-type arguments (§8.10).
To store and process objects in arrays (§8.11).
5/24/2017
COSC-1336, Lecture 9
91
Reading suggestions

From [Liang: Introduction to Java programming:
Eight Edition, 2011 Pearson Education,
0132130807]

5/24/2017
Chapter 8 (Objects and Classes)
COSC-1336, Lecture 9
92
Coming up next

From [Liang: Introduction to Java
programming: Eight Edition, 2011 Pearson
Education, 0132130807]

5/24/2017
Chapter 10 (Thinking in Objects)
COSC-1336, Lecture 9
93
Thank you for your attention!
Questions?
5/24/2017
COSC-1336, Lecture 9
94