Documente Academic
Documente Profesional
Documente Cultură
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
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
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 objects 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 objects 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
make
easy
to maintain
Liang, Introduction
to Java fields
Programming, to
Eighth Edition,
(c) 2011classes
Pearson Education,
Inc. All
3
rights reserved. 0132130807
(8.9).
OO Programming Concepts
Example of
class
Alarm
Car
Door
Teacher
Department
Example of
object
Fire alarm
Ferrari 360
Fire door
Mohammad,
Hassan
CS, IT , IS
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
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
Kinds of classes:
Standard Class: Dont 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
Import
Import
Statements
Statements
Class
ClassComment
Comment
class
Class
ClassName
Name
Data
DataMembers
Members
Methods
Methods
(incl.
(incl.Constructor)
Constructor)
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
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
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
10
Object Declaration
Class
ClassName
Name
This
class
must
This class mustbe
be
defined
before
this
defined before this
declaration
declarationcan
canbe
be
stated.
stated.
Student
More
Examples
Object Name
One object is declared
here.
jan;
Account customer;
Student jan, jim, jon;
Vehicle car1, car2;
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
11
Object Creation
Object Name
Name of the object we
are creating here.
Class Name
An instance of this class
is created.
jan = new
More
Examples
Student (
Argument
No arguments are used
here.
);
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
12
1
2
Student
Student
hussain
hussain
hussain;
hussain;
= new
new Student(
Student( );
);
=
1.1.The
Theidentifier
identifierhussain
hussainisis
declared
declaredand
andspace
spaceisis
allocated
allocatedininmemory.
memory.
hussain
: Student
2.2.AAStudent
Studentobject
objectisiscreated
created
and
the
identifier
hussain
and the identifier hussainisis
set
settotorefer
refertotoit.it.
Student
Create an object
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
13
14
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
CLASS
ownerName
Data member
getOwnerName( )
setOwnerName(String)
bike1
Methods
bike2
OBJECTS
ownerName= Adam Smith
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
16
return ownerName;
ownerName = name;
class BicycleRegistration {
public static void main(String[] args)
{
Bicycle bike1, bike2;
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.
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
class TestAccount{
Account acct;
String
acct.add(25.00);
acct.deduct(50);
//Output some information
System.out.println("has $ " +
acct.getBalance() + " left in the
bank");
}
21
Trace Code
class Circle {
/** The radius of this circle */
double radius = 1.0;
/** Construct a circle object */
public Circle() {
}
Data field
Constructors
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
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
23
animation
myCircle
no value
: 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
: Circle
radius: 5.0
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
25
animation
: 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
: 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
: Circle
yourCircle.radius = 100;
radius: 5.0
: Circle
radius: 1.0
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
28
animation
: Circle
yourCircle.radius = 100;
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))
30
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
31
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
32
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);
}
}
34
Primitive type
int i = 1
Object type
Circle c
reference
c: Circle
radius = 1
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
35
After:
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
37
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
38
java.util.Date
+Date()
+Date(elapseTime: long)
+toString(): String
+getTime(): long
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
39
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
40
+Random()
+Random(seed: long)
+nextInt(): int
+nextInt(n: int): int
+nextLong(): long
+nextDouble(): double
+nextFloat(): float
+nextBoolean(): boolean
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
41
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
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
43
44
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
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
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
: 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
Set size property
: 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
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
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" Set size property
width: 200
height: 150
visible:
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
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
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
53
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
54
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
55
circle1
radius = 1
numberOfObjects = 2
Circle
radius: double
numberOfObjects: int
getNumberOfObjects(): int
+getArea(): double
instantiate
UML Notation:
+: public variables or methods
underline: static variables or methods
Memory
1
radius
numberOfObjects
radius
circle2
radius = 5
numberOfObjects = 2
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
56
57
58
public
The class, data, or method is visible to any class in any
package.
private
59
Accessibility Example
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
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
61
Example of
Data Field Encapsulation
The - sign indicates
private modifier
Circle
-radius: double
-numberOfObjects: int
+Circle()
+Circle(radius: double)
+getRadius(): double
+getNumberOfObject(): int
+getArea(): double
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
62
it meansby
a duplicate
of an
object istype
NOT
Passing
value for
primitive
created
in thevalue
called is
method.
value
(the
passed to the
parameter)
63
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
student
Memory Allocation
student
2
Receiving side
Passing side
:Student
:LibraryCard
name
owner
Joan Java
email
borrowCnt
jj@javauniv.edu
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
card2
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
student
LibraryCard card2;
st
card2
Passing Side
class LibraryCard {
private Student owner;
public void setOwner(Student st) {
}
owner = st;
: LibraryCard
owner
name
Receiving Side
Jon Java
borrowCnt
Argument is passed
: Student
email
jj@javauniv.edu
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;
}
classLibrarian{
publicstaticvoidmain(String[]args){
Studentstud;
stud =newStudent();
stud.setName("JonJava");
stud.setEmail("jj@javauniv.edu");
LibraryCardcard1,card2;
card1=newLibraryCard();
card1.setOwner(stud);
card1.checkOut(3);
card2=newLibraryCard();
card2.setOwner(stud);//thesamestudentistheownerofthe
secondcard,too
System.out.println("Card1Info:");
System.out.println(card1.toString()+"\n");
System.out.println("Card2Info:");
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
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
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
71
class Person {
The
ThePerson
Personclass
classsupports
supports
the
set
methods
and
the set methods andget
get
methods.
methods.
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
72
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
A
A
Person[ ]
person;
Only
Onlythe
thename
nameperson
person
isisdeclared,
no
array
declared, no arrayisis
allocated
allocatedyet.
yet.
person
State
of
Memor
y
After A
A is executed
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Person[ ]
B
B
person;
Now
Nowthe
thearray
arrayfor
forstoring
storing
20
Person
objects
20 Person objectsisis
created,
created,but
butthe
thePerson
Person
objects
themselves
objects themselvesare
are
not
yet
created.
not yet created.
person
0
State
of
Memor
y
16 17 18 19
After B
B is executed
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Person[ ]
person;
C
C
One
OnePerson
Personobject
objectisis
created
createdand
andthe
thereference
reference
totothis
object
is
placed
this object is placedinin
position
position0.0.
person
0
State
of
Memor
y
16 17 18 19
: Person
Person
Not Given
o
U
After C
C is executed
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
Liang, Introduction to Java Programming, Eighth Edition, (c) 2011 Pearson Education, Inc. All
rights reserved. 0132130807
}
}
}