Transcript class
Chapter 8 Objects and Classes
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
1
Motivations
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?
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
2
Objectives
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).
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).
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
3
OO Programming Concepts
Object-oriented programming (OOP) involves programming
using Classes and Objects.
•A class is used to describe something in the world, such as
occurrences, things, external entities, roles, organization
units, places or structures.
A class describes the structure and behavior of a set of
similar objects.
It is often described as a template, generalized
description, pattern or blueprint for an object, as opposed
to the actual object, itself.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
4
Once a class of items is defined, a specific instance of
the class can be defined. An instance is also called
“object”.
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,
in other words what the object does.
In other words an object is a software bundle of
variables and related methods.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
5
Class and Object Example
The table gives some examples of classes and objects
Type
Example of class
Occurrence
Things
External entities
Roles
Alarm
Car
Door
Teacher
Organizational
units
Department
Example of
object
Fire alarm
Ferrari 360
Fire door
Mohammad,
Hassan
CS, IT , IS
Real World Objects
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
6
UML Class and Object Diagrams:
A class diagram is simply a rectangle divided into three
compartments. The topmost compartment contains the name of the
class. The middle compartment contains a list of attributes (member
variables), and the bottom compartment contains a list of operations
(member functions). The purpose of a class diagram is to show the
classes within a model.
UML Class Diagram
Student
Name: String
getName(): String
Class name
Data fields
methods
setName()
S1: Student
Name = “Ahmed”
S2: Student
Name=”Ali”
S3: Student
Name=”Suhel”
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
UML notation
for objects
3 Objects of
Student class
7
Kinds of classes:
Standard Class: Don’t reinvent the wheel. When there are existing
objects that satisfy our needs, use them. Learning how to use standard
Java classes is the first step toward mastering OOP. Some of the
standard classes are JOptionPane , String , Scanner etc
Programmer defined Class: Using just the String, JOptionPane,
Scanner, JFrame and other standard classes will not meet all of our
needs. We need to be able to define our own classes customized for
our applications. Classes we define ourselves are called programmerdefined classes
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
8
Template for Class Definition
Import
Statements
Class Comment
class
{
Class Name
Data Members
Methods
(incl. Constructor)
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
9
Example of a Class
import java.util.*;
//student class definition
class Student {
/** The name of a student */
String name ;
/** Methods of Student class */
public void setName(String n) {
name=n;
}
Data field
Methods
public String getName() {
return name;
}
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
10
Object Declaration
Class Name
This class must be
defined before this
declaration can be stated.
Student
More
Examples
Account
Student
Vehicle
Object Name
One object is declared
here.
jan;
customer;
jan, jim, jon;
car1, car2;
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
11
Object Creation
Class Name
An instance of this class
is created.
Object Name
Name of the object we
are creating here.
jan = new
More
Examples
Student (
Argument
No arguments are used
here.
);
customer = new Account();
jon
= new Student(“John Java”);
car1
= new Vehicle( );
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
12
Declaration vs. Creation
1
Student
hussain;
2
hussain
=
new
Student( );
1. The identifier hussain is
declared and space is
allocated in memory.
hussain
1
: Student
2
2. A Student object is created
and the identifier hussain is
set to refer to it.
Declaration and Creation in one step
Assign object reference
Student
Create an object
hussain= new Student();
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
13
Accessing members of a class
. (dot) operator is used to access public members of a class
A general syntax to access public members of a class is as follows
// s is object of Student class
Student
s= new Student();
Referencing the object’s data:
objectRefVar.data
e.g., s.name=“Ali”; // accessing public data member
Invoking the object’s method:
objectRefVar.methodName(arguments)
e.g., s.setName(“Ahmad”); // accessing method
s.getName(); // accessing method
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
14
Example 1: Defining Classes and Creating Objects
Objective: Demonstrate creating objects, accessing
data, and using methods.
//student class definition
class Student {
/** name is a data member to
store name of a student */
String name ;
/** Methods of Student class */
public void setName(String n) {
name=n; }
public String getName() {
return name; }
}
//Test class Teststudent definition
class TestStudent {
public static void main (String [] args)
{
// Creating object
Student s = new Student ();
s.name=“Ali”;
System.out.println(“Name:” + s.name);
s.setName(“Ahmad”);
System.out.println(“Name:” + s.getName());
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
15
Second Example: Using the Bicycle Class
Bicycle
CLASS
ownerName
Data member
getOwnerName( )
setOwnerName(String)
bike1
Methods
bike2
OBJECTS
ownerName= “Adam Smith”
ownerName = “Ben Jones”
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
16
Example 2: Defining Classes and Creating Objects
Objective: Demonstrate creating objects, accessing data,
and using methods.
public static void main(String[] args)
{
class Bicycle {
Bicycle bike1, bike2;
// Data Member
private String ownerName;
//Returns name of this bicycle's owner
public String getOwnerName( ) {
}
return ownerName;
//Assigns name of this bicycle's owner
public void setOwnerName(String name)
{
}
}
class BicycleRegistration {
ownerName = name;
String
owner1, owner2;
bike1 = new Bicycle( );
//Create and assign values to bike1
bike1.setOwnerName("Adam Smith");
bike2 = new Bicycle( );
//Create and assign values to bike2
bike2.setOwnerName("Ben Jones");
owner1 = bike1.getOwnerName( );
//Output the information
owner2 = bike2.getOwnerName( );
System.out.println(owner1 + " owns a
bicycle.");
System.out.println(owner2 + " also
owns a bicycle.");
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
17
Constructors
The constructor method is like a normal public method
except that it shares the same name as the class and it
has no return value not even void since constructors
never return a value. It can have none, one or many
parameters. Constructors are a special kind of methods
that are invoked to construct objects.
Normally for a constructor method to be useful we
would design it so that it expects parameters. The values
passed through these parameters can be used to set the
values of the private fields.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
18
Constructors, cont.
A constructor with no parameters is referred to as a
no-arg constructor.
Point to be noted about
constructor.
1. Constructors must have the same name as the class
itself.
2. Constructors do not have a return type—not even
void.
3. Constructors are invoked (called) using the new
operator when an object is created.
4. Constructors play the role of initializing objects.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
19
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. This constructor,
called a default constructor, is provided
automatically only if no constructors are explicitly
declared in the class.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
20
Example 3: Defining Classes with constructors and Creating Objects.
class Account {
class TestAccount{
private String ownerName;
private double balance;
public Account( ) {
ownerName = "Unassigned";
balance = 0.0;
}
public void add(double amt) {
balance = balance + amt;
}
/* This sample program uses both
the Bicycle and Account classes */
public static void main(String[] args)
{
Account acct;
String
public void deduct(double amt) {
balance = balance - amt;
}
acct = new Account( );
acct.setOwnerName(myName);
acct.setBalance(250.00);
public void setBalance (double bal) {
balance = bal;
}
public void setOwnerName (String name) {
ownerName = name;
}
public double getBalance( ) {
return balance;
}
myName = "Jon Java";
acct.add(25.00);
acct.deduct(50);
//Output some information
System.out.println("has $ " +
acct.getBalance() + " left in the
bank");
}
}
public String getOwnerName( ) {
return ownerName;
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
21
Trace Code
class Circle {
/** The radius of this circle */
double radius = 1.0;
/** Construct a circle object */
public Circle() {
}
Data field
Constructors
/** Construct a circle object */
public Circle(double newRadius) {
radius = newRadius;
}
/** Return the area of this circle */
public double getArea() {
return radius * radius * 3.14159;
}
Method
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
22
animation
Trace Code
Another Example
Circle myCircle = new Circle(5.0);
Declare myCircle
myCircle
no value
Circle yourCircle = new Circle();
yourCircle.radius = 100;
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
23
animation
Trace Code, cont.
Circle myCircle = new Circle(5.0);
myCircle
no value
Circle yourCircle = new Circle();
: Circle
yourCircle.radius = 100;
radius: 5.0
Create a circle
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
24
animation
Trace Code, cont.
Circle myCircle = new Circle(5.0);
myCircle reference value
Circle yourCircle = new Circle();
yourCircle.radius = 100;
Assign object reference
to myCircle
: Circle
radius: 5.0
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
25
animation
Trace Code, cont.
Circle myCircle = new Circle(5.0);
myCircle reference value
Circle yourCircle = new Circle();
yourCircle.radius = 100;
: Circle
radius: 5.0
yourCircle
no value
Declare yourCircle
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
26
animation
Trace Code, cont.
Circle myCircle = new Circle(5.0);
myCircle reference value
Circle yourCircle = new Circle();
: Circle
yourCircle.radius = 100;
radius: 5.0
no value
yourCircle
: Circle
Create a new
Circle object
radius: 0.0
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
27
animation
Trace Code, cont.
Circle myCircle = new Circle(5.0);
myCircle reference value
Circle yourCircle = new Circle();
: Circle
yourCircle.radius = 100;
radius: 5.0
yourCircle reference value
Assign object reference
to yourCircle
: Circle
radius: 1.0
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
28
animation
Trace Code, cont.
Circle myCircle = new Circle(5.0);
myCircle reference value
Circle yourCircle = new Circle();
yourCircle.radius = 100;
: Circle
radius: 5.0
yourCircle reference value
: Circle
Change radius in
yourCircle
radius: 100.0
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
29
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.”
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
30
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 {
String name; // name has default value null
int age; // age has default value 0
boolean isScienceMajor; // isScienceMajor has default value false
char gender; // c has default value '\u0000'
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
31
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.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
32
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. However, Java assigns no default value to a
local variable inside a method.
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);
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
33
Example
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
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
34
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
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
35
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:
After:
c1
c1
c2
c2
c1: Circle
C2: Circle
c1: Circle
C2: Circle
radius = 5
radius = 9
radius = 5
radius = 9
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
36
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. Garbage is
automatically collected by JVM.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
37
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.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
38
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
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.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
39
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 Sun Mar 09 13:50:19 EST 2003.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
40
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.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
41
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
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
42
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.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
43
// Generate frame using standard class JFrame
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); }
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
44
animation
Declare, create,
and assign in one
statement
Trace Code
JFrame frame1 = new JFrame();
frame1.setTitle("Window 1");
frame1.setSize(200, 150);
frame1.setVisible(true); JFrame
frame2 = new JFrame();
frame2.setTitle("Window 2");
frame2.setSize(200, 150);
frame2.setVisible(true);
frame1 reference
: JFrame
title:
width:
height:
visible:
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
45
animation
Trace Code
JFrame frame1 = new JFrame();
frame1.setTitle("Window 1");
frame1.setSize(200, 150);
frame1.setVisible(true); JFrame
frame2 = new JFrame();
frame2.setTitle("Window 2");
frame2.setSize(200, 150);
frame2.setVisible(true);
frame1 reference
Set title property
: JFrame
title: "Window 1"
width:
height:
visible:
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
46
animation
Trace Code
JFrame frame1 = new JFrame();
frame1.setTitle("Window 1");
frame1.setSize(200, 150);
frame1.setVisible(true);
JFrame frame2 = new JFrame();
frame2.setTitle("Window 2");
frame2.setSize(200, 150);
frame2.setVisible(true);
frame1 reference
: JFrame
title: "Window 1"
width: 200
height: 150
visible:
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Set size property
47
animation
Trace Code
JFrame frame1 = new JFrame();
frame1.setTitle("Window 1");
frame1.setSize(200, 150);
frame1.setVisible(true);
JFrame frame2 = new JFrame();
frame2.setTitle("Window 2");
frame2.setSize(200, 150);
frame2.setVisible(true);
frame1 reference
: JFrame
title: "Window 1"
width: 200
height: 150
visible: true
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Set visible
property
48
animation
Trace Code
JFrame frame1 = new JFrame();
frame1.setTitle("Window 1");
frame1.setSize(200, 150);
frame1.setVisible(true);
JFrame frame2 = new JFrame();
frame2.setTitle("Window 2");
frame2.setSize(200, 150);
frame2.setVisible(true);
frame1 reference
: JFrame
title: "Window 1"
width: 200
height: 150
visible: true
frame2 reference
Declare, create,
and assign in one
statement
: JFrame
title:
width:
height:
visible:
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
49
animation
Trace Code
JFrame frame1 = new JFrame();
frame1.setTitle("Window 1");
frame1.setSize(200, 150);
frame1.setVisible(true);
JFrame frame2 = new JFrame();
frame2.setTitle("Window 2");
frame2.setSize(200, 150);
frame2.setVisible(true);
frame1 reference
: JFrame
title: "Window 1"
width: 200
height: 150
visible: true
frame2 reference
: JFrame
title: "Window 2"
width:
height:
visible:
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Set title property
50
animation
Trace Code
JFrame frame1 = new JFrame();
frame1.setTitle("Window 1");
frame1.setSize(200, 150);
frame1.setVisible(true);
JFrame frame2 = new JFrame();
frame2.setTitle("Window 2");
frame2.setSize(200, 150);
frame2.setVisible(true);
frame1 reference
: JFrame
title: "Window 1"
width: 200
height: 150
visible: true
frame2 reference
: JFrame
title: "Window 2"
width: 200
height: 150
visible:
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Set size property
51
animation
Trace Code
JFrame frame1 = new JFrame();
frame1.setTitle("Window 1");
frame1.setSize(200, 150);
frame1.setVisible(true);
JFrame frame2 = new JFrame();
frame2.setTitle("Window 2");
frame2.setSize(200, 150);
frame2.setVisible(true);
frame1 reference
: JFrame
title: "Window 1"
width: 200
height: 150
visible: true
frame2 reference
: JFrame
title: "Window 2"
width: 200
height: 150
visible: true
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Set visible
property
52
Instance Variables, and Methods
Instance variables belong to a specific instance.
Instance methods are invoked by an instance of
the class.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
53
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.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
54
Static Variables, Constants,
and Methods, cont.
To declare static variables, constants, and methods,
use the static modifier.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
55
Static Variables, Constants,
and Methods, cont.
instantiate
circle1
radius = 1
numberOfObjects = 2
Circle
Memory
1
radius: double
numberOfObjects: int
getNumberOfObjects(): int
+getArea(): double
instantiate
UML Notation:
+: public variables or methods
underline: static variables or methods
radius
2
numberOfObjects
5
radius
After two Circle
objects were created,
numberOfObjects
is 2.
circle2
radius = 5
numberOfObjects = 2
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
56
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.
public class Circle2 {
double radius; /** The radius of the circle */
static int numberOfObjects = 0; /** No of objects created */
/** Construct a circle with radius 1 */
Circle2() {
radius = 1.0;
numberOfObjects++; }
/** 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; }
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
57
public class TestCircle2 { /** Main method */
public static void main(String[] args) {
System.out.println("Before creating objects");
System.out.println("The number of Circle objects is " + Circle2.numberOfObjects);
// Create c1
Circle2 c1 = new Circle2();
// Display c1 BEFORE c2 is created
System.out.println("\nAfter creating c1");
System.out.println("c1: radius (" + c1.radius + ") and number of Circle objects (" +
c1.numberOfObjects + ")");
// Create c2 Circle2
c2 = new Circle2(5); // Modify c1
c1.radius = 9; // Display c1 and c2 AFTER c2 was created
System.out.println("\nAfter creating c2 and modifying c1");
System.out.println("c1: radius (" + c1.radius + ") and number of Circle objects (" +
c1.numberOfObjects + ")");
System.out.println("c2: radius (" + c2.radius + ") and number of Circle objects (" +
c2.numberOfObjects + ")"); }
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
58
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
properties.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
59
Accessibility Example
…
Service obj = new Service();
class Service {
public int memberOne;
private int memberTwo;
public void doOne() {
obj.memberOne = 10;
…
obj.memberTwo = 20;
}
private void doTwo() {
obj.doOne();
…
obj.doTwo();
}
}
…
Client
Service
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
60
Why Data Fields Should Be
private?
To protect data.
To make class easy to maintain.
Internal details of a class are declared private and hidden from the clients.
This is information hiding.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
61
Example of
Data Field Encapsulation
Circle
The - sign indicates
private modifier
-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.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
62
Passing Objects to Methods
As
we can pass int and double values, we can
also pass an object to a method.
When we pass an object, we are actually
passing the reference (name) of an object
– it means a duplicate of an object is NOT created
in the called method.
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)
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
63
Passing Objects to a Method
Student
LibraryCard
name
email
owner
borrowCnt
Student( )
LibraryCard( )
getEmail( )
chcekOut( int )
getName( )
getNumberOfBooks( )
setEmail(String)
getOwnerName( )
setName(String)
setOwner( Student )
toString()
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
64
Passing a Student Object
student
Memory Allocation
student
1
2
Receiving side
Passing side
:Student
:LibraryCard
name
owner
“Joan Java”
email
borrowCnt
jj@javauniv”.edu”
0
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
card2
Passing a Student Object
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Passing a Student Object
LibraryCard card2;
1
student
st
card2 = new LibraryCard();
card2.setOwner(student);
card2
1
Passing Side
2
class LibraryCard {
private Student owner;
public void setOwner(Student st) {
}
owner = st;
}
2
: LibraryCard
owner
name
“Jon Java”
Receiving Side
borrowCnt
1
Argument is passed
2
Value is assigned to the
data member
: Student
0
email
“[email protected]”
State of Memory
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
class Student {
private String name;
private String email;
public Student() {
name = "Unassigned";
email = "Unassigned";
}
public String getEmail( ) {
return email;
}
public String getName( ) {
return name;
}
//Assigns the name of this student
public void setName(String studentName) {
name = studentName;
}
//Assigns the email of this student
public void setEmail(String address) {
}
}
class LibraryCard {
//student owner of this card
private Student owner;
//number of books borrowed
private int borrowCnt;
//numOfBooks are checked out
public void checkOut(int numOfBooks) {
borrowCnt = borrowCnt + numOfBooks;
}
//Returns the name of the owner of this card
public String getOwnerName( ) {
return owner.getName( );
}
//Returns the number of books borrowed
public int getNumberOfBooks( ) {
return borrowCnt;
}
//Sets the owner of this card to student
public void setOwner(Student stud) {
owner = stud;
}
//Returns the string representation of this card
public String toString( ) {
return "Owner Name: " +owner.getName( )+"\n"+
email = address;
“Email:
" + owner.getEmail( ) + "\n" +
"Books Borrowed: " + borrowCnt;
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
68
rights reserved. 0132130807
class Librarian {
public static void main( String[] args ) {
Student
stud;
stud = new Student( );
stud.setName("Jon Java");
stud.setEmail("[email protected]");
LibraryCard card1, card2;
card1 = new LibraryCard( );
card1.setOwner(stud);
card1.checkOut(3);
card2 = new LibraryCard( );
card2.setOwner(stud); //the same student is the owner of the
second card, too
System.out.println("Card1 Info:");
System.out.println(card1.toString() + "\n");
System.out.println("Card2 Info:");
System.out.println(card2.toString() + "\n");
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
69
Sharing an Object
We pass the same Student
object to card1 and card2
•
Since we are actually passing
a reference to the same
object, it results in owner of
two
LibraryCard
objects
pointing to the same Student
object
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
70
Array of Objects
In Java, in addition to arrays of primitive data types,
we can declare arrays of objects
An array of primitive data is a powerful tool, but an
array of objects is even more powerful.
The use of an array of objects allows us to model the
application more cleanly and logically.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
71
class Person {
The Person class supports
the set methods and get
methods.
private String name;
private int age;
private char gender;
public Person() {
name = "Unassigned";
age = -1;
gender=‘u’;
}
// Return Person Age
public int getAge( ) {
return age;
}
// Return Person Gender
public char getGender( ) {
return gender;
}
//Return Person Name
public String getName( ) {
return name;
}
//Assigns the name of Person
public void setName(String personName)
{ name = personName;
}
//Assigns the age of Person
public void setAge(int personAge) {
age = personAge;
}
//Assigns the Gender of Person (M/F)
public void setGender(char
personGender) {
gender = personGender;
}
}
public class Test {
public static void main (String[] args) {
Person latte;
latte = new Person( );
latte.setName("Ms. Latte");
latte.setAge(20);
latte.setGender('F');
System.out.println("Name: "+
latte.getName());
System.out.println("Age : "+
latte.getAge());
System.out.println("Sex : "+
latte.getGender());}}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
72
The Person Class
We will use Person objects to illustrate the use of an array of
objects.
Person latte;
latte = new Person( );
latte.setName("Ms. Latte");
latte.setAge(20);
latte.setGender('F');
System.out.println( "Name: " + latte.getName()
);
System.out.println( "Age : " + latte.getAge()
);
System.out.println( "Sex : " + latte.getGender() );
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Creating an Object Array - 1
Code
A
Person[ ]
person;
person = new Person[20];
person[0] = new Person( );
Only the name person is
declared, no array is
allocated yet.
person
State
of
Memory
After A is executed
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Creating an Object Array - 2
Code
Person[ ]
B
person;
person = new Person[20];
person[0] = new Person( );
Now the array for storing
20 Person objects is
created, but the Person
objects themselves are
not yet created.
person
0
1
2
3
4
16 17 18 19
State
of
Memory
After B is executed
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Creating an Object Array - 3
Code
Person[ ]
person;
person = new Person[20];
C
person[0] = new Person( );
One Person object is
created and the reference
to this object is placed in
position 0.
person
0
State
of
Memory
1
2
3
4
16 17 18 19
: Person
Person
Not Given
o
U
After C is executed
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
The Person Class
public class Test {
public static void main (String[] args) {
Person [ ]prsn=new Person [20];
Prsn[0] = new Person( );
Prsn[0].setName("Ms. Latte");
Prsn[0].setAge(20);
Prsn[0].setGender('F');
Prsn[1] = new Person( );
Prsn[1].setName("Mr. Khalid");
Prsn[1].setAge(30);
Prsn[1].setGender(‘M');
.
.
.
.
}
}
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Person Array Processing – Sample 1
Create Person objects and set up the person array.
class Test {
public static void main (String[] args) {
String name, inpStr;
int
age;
char
gender;
Person [ ]prsn=new Person [20];
for (int i = 0; i < prsn.length; i++)
{
name = JOptionPane.showInputDialog(null,"Enter name:");
age = Integer.parseInt(JOptionPane.showInputDialog(null,"Enter age:"));
inpStr = JOptionPane.showInputDialog(null,"Enter gender:");
gender = inpStr.charAt(0);
prsn[i] = new Person( );
prsn[i].setName ( name
);
prsn[i].setAge
( age
);
prsn[i].setGender( gender );
}
}
}
©The McGraw-Hill Companies,
Inc. Permission required for
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
reproduction or display.
Chapter 10 - 78 rights reserved. 0132130807