Survey
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the work of artificial intelligence, which forms the content of this project
Chapter 6 Objects and Classes
Prerequisites for Part II
She calls out to the man on the street
Sir can you help me
…
Chapter 5 Arrays
Oh think twice
It's another day for you and me In paradise
…
Chapter 6 Objects and Classes
Chapter 7 Strings
You can cover GUI after Chapter 8
Chapter 8 Inheritance and Polymorphism
Chapter 11 Getting Started with GUI Programming
Chapter 9 Abstract Classes and Interfaces
Chapter 12 Event-Driven Programming
Chapter 10 Object-Oriented Modeling
Chapter 15 Exceptions and Assertions
You can cover Exceptions and I/O after Chapter 8
Chapter 16 Simple Input and Output
Liang,Introduction to Java Programming,revised by Dai-kaiyu
1
Objectives
To understand objects and classes and use classes to model objects (§6.2).
To learn how to declare a class and how to create an object of a class (§6.3).
To understand the roles of constructors and use constructors to create objects
(§6.3).
To use UML graphical notations to describe classes and objects (§6.3).
To distinguish between object reference variables and primitive data type variables
(§6.4).
To use classes in the Java library (§6.5).
To declare private data fields with appropriate get and set methods to make class
easy to maintain (§6.6-6.8).
To develop methods with object arguments (§6.9).
To understand the difference between instance and static variables and methods
(§6.10).
To determine the scope of variables in the context of a class (§6.11).
To use the keyword this as the reference to the current object that invokes the
instance method (§6.12).
To store and process objects in arrays (§6.13).
To apply class abstraction to develop software (§6.14).
2
Liang,Introduction to Java Programming,revised by Dai-kaiyu
To declare inner classes (§6.17).
OO Programming Concepts
Object Oriented Programming (OOP)
Encapsulates data (attributes) and methods
(behaviors)
Objects: An object represents an entity in the real world
that can be distinctly identified
Allows objects to communicate
Well-defined interfaces
Liang,Introduction to Java Programming,revised by Dai-kaiyu
3
OO Programming Concepts
Procedural programming language
C is an example
Action-oriented
Functions are units of programming
Object-oriented programming language
Java is an example
Object-oriented
Classes are units of programming
Functions, or methods, are encapsulated in classes
Liang,Introduction to Java Programming,revised by Dai-kaiyu
4
OO Programming Concepts
Procedural programming language
algrithom + data structure
Object-oriented programming language
Object + messaging
Liang,Introduction to Java Programming,revised by Dai-kaiyu
5
OO Programming Concepts
Class
Programmer-defined type
Instance variable + method
Object is the instance of the Class
System analysis-Class->Object
This section discusses
How to create objects
How to use objects
OBP Vs. OOP
Liang,Introduction to Java Programming,revised by Dai-kaiyu
6
Objects
data field 1
...
radius = 5
Data field, State
Properties
State
(Properties)
data field m
findArea()
Method,
Behavior
method 1
...
Behavior
method n
(A) A generic object
(B) An example of circle 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.
Liang,Introduction to Java Programming,revised by Dai-kaiyu
7
Classes
Every Java class must extend another class
If class does not explicitly extend another class ,it extends
java.lang.Object
class implicitly extends Object(11 methods definded in it)
Class constructor
Same name as class
Initializes instance variables of a class object
Called when program instantiates an object of that class
Can take arguments, but cannot return data types (“void”
can’t either)
A constructor with no parameters is referred to as a no-arg
constructor.
Class can have several constructors, through overloading
Liang,Introduction to Java Programming,revised by Dai-kaiyu
8
Without
main()
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 findArea() {
return radius * radius * 3.14159;
}
Method
}
Liang,Introduction to Java Programming,revised by Dai-kaiyu
9
Constructors
What if there is void
Constructors are a special
kind of methods that are
invoked to construct objects.
Circle() {
}
Circle(double newRadius) {
radius = newRadius;
}
Demo Circle.java
Liang,Introduction to Java Programming,revised by Dai-kaiyu
10
Creating Objects Using Constructors
new ClassName();
Example:
new Circle();
new Circle(5.0);
Liang,Introduction to Java Programming,revised by Dai-kaiyu
11
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,revised by Dai-kaiyu
12
Constructing Objects, cont.
UML Graphical notation for classes
Circle
radius: double
UML Graphical notation for fields
UML Graphical notation for methods
findArea(): double
new Circle()
new Circle()
circle1: Circle
radius = 2
circlen: Circle
...
UML Graphical notation
for objects
radius = 5
Liang,Introduction to Java Programming,revised by Dai-kaiyu
13
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;
Liang,Introduction to Java Programming,revised by Dai-kaiyu
14
Declaring/Creating Objects
in a Single Step
ClassName objectRefVar = new ClassName();
Assign object reference
Create an object
Example:
Circle myCircle = new Circle();
Liang,Introduction to Java Programming,revised by Dai-kaiyu
15
Accessing Objects
Referencing the object’s data:
objectRefVar.data
e.g., myCircle.radius
Invoking the object’s method:
objectRefVar.methodName(arguments)
e.g., myCircle.findArea()
Liang,Introduction to Java Programming,revised by Dai-kaiyu
16
Example 6.1 Using Objects
Objective: Demonstrate creating objects,
accessing data, and using methods.
TestSimpleCircle
Liang,Introduction to Java Programming,revised by Dai-kaiyu
Run
17
Trace Code
Declare myCircle
Circle myCircle = new Circle(5.0);
myCircle
no value
SCircle yourCircle = new Circle();
yourCircle.radius = 100;
Liang,Introduction to Java Programming,revised by Dai-kaiyu
18
Trace Code, cont.
Circle myCircle = new Circle(5.0);
no value
myCircle
Circle yourCircle = new Circle();
yourCircle.radius = 100;
: Circle
radius: 5.0
Create a circle
Liang,Introduction to Java Programming,revised by Dai-kaiyu
19
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,revised by Dai-kaiyu
20
Trace Code, cont.
Circle myCircle = new Circle(5.0);
reference value
myCircle
Circle yourCircle = new Circle();
: Circle
yourCircle.radius = 100;
radius: 5.0
yourCircle
no value
Declare yourCircle
Liang,Introduction to Java Programming,revised by Dai-kaiyu
21
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,revised by Dai-kaiyu
22
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: 0.0
Liang,Introduction to Java Programming,revised by Dai-kaiyu
23
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,revised by Dai-kaiyu
24
JBuilder
Optional
See Objects in JBuilder Debugger
You can view the contents
of an object in the debugger.
myCircle
yourCircle
Liang,Introduction to Java Programming,revised by Dai-kaiyu
25
Caution
Recall that you use
Math.methodName(arguments) (e.g., Math.pow(3, 2.5))
to invoke a method in the Math class.
You can ‘t invoke findArea() using SimpleCircle.findArea. findArea()
is non-static. It must be invoked from an object using
objectRefVar.methodName(arguments) (e.g., myCircle.findArea()).
More explanations will be given in Section 6.7, “Static Variables, Constants, and
Methods.”
Liang,Introduction to Java Programming,revised by Dai-kaiyu
26
The null Value
If a variable of a reference type does not
reference any object, the variable holds a
special literal value, null.
Reference an object that has not been created
would cause a runtime NullPointerException.
Liang,Introduction to Java Programming,revised by Dai-kaiyu
27
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
'\u0000' for a char type.
Java assigns no default value to a local
variable inside a method.
Liang,Introduction to Java Programming,revised by Dai-kaiyu
28
Example
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'
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,revised by Dai-kaiyu
29
Example
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,revised by Dai-kaiyu
30
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,revised by Dai-kaiyu
31
Copying Variables of Primitive Data
Types and Object Types
Primitive type assignment
i=j
Object type assignment
c1 = c2
Before:
After:
i
1
i
2
c1
c1
j
2
j
2
c2
c2
Before:
After:
c1: Circle
c2: Circle
radius = 5
radius = 9
Liang,Introduction to Java Programming,revised by Dai-kaiyu
32
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 useful. This object is known as
garbage. Garbage is automatically
collected by JVM.
Liang,Introduction to Java Programming,revised by Dai-kaiyu
33
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 Java VM will automatically
collect the space if the object is not
referenced by any variable.
Liang,Introduction to Java Programming,revised by Dai-kaiyu
34
Using Classes from the Java Library
Example 6.1 declared the SimpleCircle class
and created objects from the class. Often you
will use the classes in the Java library to
develop programs. You learned to obtain the
current time using System.currentTimeMillis()
in Example 2.5, “Displaying Current Time.”
You used the division and remainder operators
to extract current second, minute, and hour.
Liang,Introduction to Java Programming,revised by Dai-kaiyu
35
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. 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,revised by Dai-kaiyu
36
Using the JFrame Class
Objective: Demonstrate using classes from
the Java library. Use the JFrame class in the
javax.swing package to create two frames;
use the methods in the JFrame class to set the
title, size and location of the frames and to
display the frames.
TestFrame
Liang,Introduction to Java Programming,revised by Dai-kaiyu
Run
37
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);
Declare, create,
and assign in one
statement
frame1 reference
: JFrame
title:
width:
height:
visible:
Liang,Introduction to Java Programming,revised by Dai-kaiyu
38
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,revised by Dai-kaiyu
39
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,revised by Dai-kaiyu
Set size property
40
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,revised by Dai-kaiyu
Set visible
property
41
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,revised by Dai-kaiyu
42
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,revised by Dai-kaiyu
Set title property
43
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,revised by Dai-kaiyu
Set size property
44
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,revised by Dai-kaiyu
Set visible
property
45
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,revised by Dai-kaiyu
46
package p1;
package p2;
public class C1 {
public int x;
int y;
private int z;
public void m1() {
}
void m2() {
}
private void m3() {
}
public class C2 {
C1 o = new C1();
can access o.x;
can access o.y;
cannot access o.z;
public class C3 {
C1 o = new C1();
can access o.x;
cannot 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();
}
}
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.
even the class is public, but the member is default modifier,
the class not in the same package can’t access it
Liang,Introduction to Java Programming,revised by Dai-kaiyu
47
Caution
Private not to class(except inner class)
Visibility modifier not used for local
variables
Private can modify constructor
package p1;
class C1{
package p2;
public class C2{
…
}
public class C3{
can access C1;
}
cannot access C1;
}
Liang,Introduction to Java Programming,revised by Dai-kaiyu
48
Encapsulation & Access modifiers
Encapsulation is the concept of hiding the internal details of
an object
Access modifiers are used to control access to object or class
data
Liang,Introduction to Java Programming,revised by Dai-kaiyu
49
Some issues
Helper class
not modified by “public”, so can just be accessed by the class
in the same package. They support the reusable class
The sequence of finding the class (when compile or
excute)
System will find them
Standard classes :rt.jar
Extended classes
Class path
automatically
- classpath (can refer to a .zip or a .jar file)
Classpath environment variables
Liang,Introduction to Java Programming,revised by Dai-kaiyu
50
Why Data Fields Should Be private?
To protect data.
To make class easy to maintain.
Getter (or accessor ) and setter (mutator) method
public returnType getPropertyName()
public boolean isPropertyName()
public void setPropertyName (dataType propertyValue)
Liang,Introduction to Java Programming,revised by Dai-kaiyu
51
Example of
Data Field Encapsulation
In this example, private data are used for the radius
and the accessor methods getRadius and setRadius
are provided for the clients to retrieve and modify the
radius.
Circle
TestCircle
Liang,Introduction to Java Programming,revised by Dai-kaiyu
Run
52
Immutable Objects and Classes
If the contents of an object cannot be changed once the
object is created, the object is called an immutable object and
its class is called an immutable class.
A class with all private data fields and without mutators is
not necessary to be immutable. For example, the following
class Student has all private data fields and no mutators, but it
is mutable.
For a class to be immutable, it must mark all data fields
private and provide no mutator methods and no accessor
methods that would return a reference to a mutable data field
object.
Liang,Introduction to Java Programming,revised by Dai-kaiyu
53
Example
public class BirthDate {
private int year;
private int month;
private int day;
public class Student {
private int id;
private BirthDate birthDate;
public Student(int ssn,
int year, int month, int day) {
id = ssn;
birthDate = new BirthDate(year, month, day);
}
public BirthDate(int newYear,
int newMonth, int newDay) {
year = newYear;
month = newMonth;
day = newDay;
}
public int getId() {
return id;
}
public BirthDate getBirthDate() {
return birthDate;
}
}
public void setYear(int newYear) {
year = newYear;
}
}
public class Test {
public static void main(String[] args) {
Student student = new Student(111223333, 1970, 5, 3);
BirthDate date = student.getBirthDate();
date.setYear(2010); // Now the student birth year is changed!
}
}
Liang,Introduction to Java Programming,revised by Dai-kaiyu
54
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)
TestPassObject
Liang,Introduction to Java Programming,revised by Dai-kaiyu
Run
55
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
Heap
A circle
object
Liang,Introduction to Java Programming,revised by Dai-kaiyu
56
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,revised by Dai-kaiyu
57
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.
Liang,Introduction to Java Programming,revised by Dai-kaiyu
58
Static Variables, Constants,
and Methods, cont.
UML Notation:
+: public variables or methods
-: private variables or methods
underline: static variables or methods
Memory
instantiate
circle1
-radius = 1
-numberOfObjects = 2
CircleWithStaticVariableAndMethod
1
-radius: double
-numberOfObjects: int
+getRadius(): double
+setRadius(radius: double): void
+getNumberOfObjects(): int
+findArea(): double
instantiate
radius
2
numberOfObjects
5
radius
circle2
-radius = 5
-numberOfObjects = 2
Liang,Introduction to Java Programming,revised by Dai-kaiyu
59
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
numOfObjects to track the number of Circle objects created.
CircleWithStaticVariableAndMethod
TestCircleWithStaticVariableAndMethod
Liang,Introduction to Java Programming,revised by Dai-kaiyu
Run
60
Static modifier
To declare a class constant ,add the final
keyword in the static variable declaration
Recomment access the static variable and
methods using ClassName.variable(or method)
instance variables and methods can only be
used from instance methods, not from static
methods!
Liang,Introduction to Java Programming,revised by Dai-kaiyu
61
Scope of Variables
The scope of instance and static variables is the
entire class. They can be declared anywhere
inside a class.
The scope of a local variable starts from its
declaration and continues to the end of the block
that contains the variable. A local variable must
be initialized explicitly before it can be used.
Liang,Introduction to Java Programming,revised by Dai-kaiyu
62
The this Keyword
Use this to refer to the object that invokes
the instance method.
Use this to refer to an instance data field.
Use this to invoke an overloaded
constructor of the same class.
Liang,Introduction to Java Programming,revised by Dai-kaiyu
63
Serving as Proxy to the Calling Object
class Foo {
int i = 5;
static double k = 0;
Suppose that f1 and f2 are two objects of Foo.
Invoking f1.setI(10) is to execute
f1.i = 10, where this is replaced by f1
void setI(int i) {
this.i = i;
}
Invoking f2.setI(45) is to execute
f2.i = 45, where this is replaced by f2
static void setK(double k) {
Foo.k = k;
}
}
Liang,Introduction to Java Programming,revised by Dai-kaiyu
64
Calling Overloaded Constructor
public class Circle {
private double radius;
public Circle(double radius) {
this.radius = radius;
}
this must be explicitly used to reference the data
field radius of the object being constructed
public Circle() {
this(1.0);
}
Appear before other
statements
this is used to invoke another constructor
public double findArea() {
return this.radius * this.radius * Math.PI;
}
}
Every instance variable belongs to an instance represented by this,
which is normally omitted
Liang,Introduction to Java Programming,revised by Dai-kaiyu
65
Array of Objects
Circle[] circleArray = new Circle[10];
An array of objects is actually an array of
reference variables.
So invoking circleArray[1].findArea() involves two
levels of referencing as shown in the next figure.
circleArray references to the entire array. circleArray[1]
references to a Circle object.
Liang,Introduction to Java Programming,revised by Dai-kaiyu
66
Array of Objects, cont.
Circle[] circleArray = new Circle[10];
circleArray
reference
circleArray[0]
circleArray[1]
Circle object 0
…
Circle object 1
circleArray[9]
Circle object 9
Liang,Introduction to Java Programming,revised by Dai-kaiyu
67
Array of Objects, cont.
Example 6.2: Summarizing the areas
of the circles
TotalArea
Liang,Introduction to Java Programming,revised by Dai-kaiyu
Run
68
Class Abstraction and Encapsulation
Class abstraction means to separate class
implementation from the use of the class.
The creator of the class provides a description of the class and
let the user know how the class can be used.
The user of the class does not need to know how the class is
implemented. The detail of implementation is encapsulated and
hidden from the user.
Class implementation
is like a black box
hidden from the clients
Class
Class Contract
(Signatures of
public methods and
public constants)
Liang,Introduction to Java Programming,revised by Dai-kaiyu
Clients use the
class through the
contract of the class
69
Example 6.3 The Loan Class
Loan
-annualInterestRate: double
The annual interest rate of the loan (default: 2.5).
-numberOfYears: int
The number of years for the loan (default: 1)
-loanAmount: double
The loan amount (default: 1000)..
-loanDate: Date
The date this loan was created.
+Loan()
Constructs a default loan object.
+Loan(annualInterestRate: double,
numberOfYears: int,
loanAmount: double)
Constructs a loan with specified interest rate, years, and
loan amount.
+getAnnualInterestRate(): double
Returns the annual interest rate of this loan.
+getNumberOfYears(): int
Returns the number of the years of this loan.
+getLoanAmount(): double
Returns the amount of this loan.
+getLoanDate(): Date
Returns the date of the creation of this loan.
Loan
TestLoanClass
Run
+setAnnualInterestRate(
Sets a new annual interest rate to this loan.
annualInterestRate: double): void
Sets a new number of years to this loan.
+setNumberOfYears(
numberOfYears: int): void
+setLoanAmount(
loanAmount: double): void
Sets a new amount to this loan.
+monthlyPayment(): double
Returns the monthly payment of this loan.
+totalPayment(): double
Returns the total payment of this loan.
Liang,Introduction to Java Programming,revised by Dai-kaiyu
70
Example 6.4 The StackOfIntegers Class
StackOfIntegers
capacity - 1
.
.
.
-elements: int[]
-size: int
size - 1
+StackOfIntegers()
+StackOfIntegers(capacity: int)
+empty(): boolean
+peek(): int
+push(element: int): int
+pop(): int
.
.
.
[1]
+getSize(): int
[0]
StackOfIntegers
TestStackOfIntegers
Run
Liang,Introduction to Java Programming,revised by Dai-kaiyu
71
Data Abstraction and Encapsulation
Encapsulation (data hiding)
Stack data structure
Last in-first out (LIFO)
Developer creates stack
• Hides stack’s implementation details from clients
Data abstraction
• Abstract data types (ADTs)
Liang,Introduction to Java Programming,revised by Dai-kaiyu
72
Queue Abstract Data Type
Abstract Data Type (ADT)
Queue
Line at grocery store
First-in, first-out (FIFO)
• Enqueue to place objects in queue
• Dequeue to remove object from queue
• Enqueue and dequeue hide internal data representation
Liang,Introduction to Java Programming,revised by Dai-kaiyu
73
Inner Classes
Inner class: A class is a member of another class.
Advantages: In some applications, you can use an
Using outerClass.this
inner class to make programs simple.
if the same name
An inner class can reference the data and
methods defined in the outer class in which it
nests, even the ones modified by private. so you
do not need to pass the reference of the outer
class to the constructor of the inner class.
Frequently used with GUI handling
Liang,Introduction to Java Programming,revised by Dai-kaiyu
74
Inner Classes (cont.)
Inner classes can make programs simple
and concise.
An inner class supports the work of its
containing outer class and is compiled
into a class named
OutClassName$InnerClassName.class.
For example, the inner class InnerClass in
ShowInnerClass is compiled into
ShowInnerClass$InnerClass.class.
Liang,Introduction to Java Programming,revised by Dai-kaiyu
75
Inner Classes (cont.)
An inner class can be declared public,
protected, or private subject to the same
visibility rules applied to a member of the
class.
An inner class can be declared static. A
static inner class can be accessed using
the outer class name. A static inner class
cannot access nonstatic members of the
outer class
Liang,Introduction to Java Programming,revised by Dai-kaiyu
76
Inner Classes (cont.)
Create an object of an inner class from another class, if it is
non-static.
OuterClass outerObject = new OuterClass(parameters);
OuterClass.InnerClass innerObject = outerObject.new InnerClass( );
If the inner class is static, use the following syntax to
create an object for it.
OuterClass.InnerClass innerObject = new OuterClass.InnerClass( );
Liang,Introduction to Java Programming,revised by Dai-kaiyu
77
Inner Classes (cont.)
More about inner classes
Static inner classes can’t refer to the non-static
members of outer class.
Non-static inner classes can’t have static members.
The inner classes even can be defined in a method
The outer calss can’t refer to the member of inner
class directly
ShowInnerClass.java v2
Liang,Introduction to Java Programming,revised by Dai-kaiyu
78
A taste of Simple design pattern
Singleton
A class just has one instance
The instance is created by itself
The whole system can use it
Liang,Introduction to Java Programming,revised by Dai-kaiyu
Usage:resource
manage
79
A taste of Simple design pattern
EagerSingleton
EagerSingleton.java
LazySingleton
They can’t be
inherited
LazySingleton.java
SingletonTest.java
Liang,Introduction to Java Programming,revised by Dai-kaiyu
80