Interfaces are more flexible than abstract classes,
because a subclass can extend only one superclass,
but implement any number of interfaces. However,
interfaces cannot contain concrete methods. You
can combine the virtues of interfaces and abstract
classes by creating an interface with a companion
abstract class that implements the interface. So you
can use the interface or its companion class
whichever is more convenient
179 trang |
Chia sẻ: dntpro1256 | Lượt xem: 671 | Lượt tải: 0
Bạn đang xem trước 20 trang tài liệu Advanced Programming Language - Chapter II: Objects - Oriented Programming, để xem tài liệu hoàn chỉnh bạn click vào nút DOWNLOAD ở trên
as follows:
public boolean equals(Object obj) {
return (this == obj);
}
For example, the
equals method is
overridden in
the Circle
class.
public boolean equals(Object o) {
if (o instanceof Circle) {
return radius == ((Circle)o).radius;
}
else
return false;
}
Optional
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 92
NOTE
The == comparison operator is used for
comparing two primitive data type values or for
determining whether two objects have the same
references. The equals method is intended to
test whether two objects have the same
contents, provided that the method is modified
in the defining class of the objects. The ==
operator is stronger than the equals method, in
that the == operator checks whether the two
reference variables refer to the same object.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 93
The hashCode() method
Invoking hashCode() on an object returns the hash
code of the object. Hash code is an integer, which can
be used to store the object in a hash set so that it can be
located quickly. Hash sets will be introduced in
Chapter 22, “Java Collections Framework.” The
hashCode implemented in the Object class returns the
internal memory address of the object in hexadecimal.
Your class should override the hashCode method
whenever the equals method is overridden. By
contract, if two objects are equal, their hash codes must
be same.
Optional
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 94
The finalize, clone, and
getClass Methods
The finalize method is invoked by the garbage collector
on an object when the object becomes garbage.
The clone() method copies an object.
The getClass() method returns an instance of the
java.lang.Class class, which contains the information
about the class for the object. Before an object is created,
its defining class is loaded and the JVM automatically
creates an instance of java.lang.Class for the class. From
this instance, you can discover the information about the
class at runtime.
Optional
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 95
The finalization Demo
The finalize method is invoked by the JVM.
You should never write the code to invoke it in
your program. For this reason, the protected
modifier is appropriate.
Optional
FinalizationDemo Run
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 96
Hiding Fields and Static Methods
You can override an instance method, but you cannot
override a field (instance or static) or a static method.
If you declare a field or a static method in a subclass
with the same name as one in the superclass, the one
in the superclass is hidden, but it still exists. The two
fields or static methods are independent. You can
reference the hidden field or static method using the
super keyword in the subclass. The hidden field or
method can also be accessed via a reference variable
of the superclass’s type.
Optional
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 97
Hiding Fields and Static Methods, cont.
When invoking an instance method from a reference
variable, the actual class of the object referenced by
the variable decides which implementation of the
method is used at runtime. When accessing a field or
a static method, the declared type of the reference
variable decides which method is used at compilation
time.
HidingDemo Run
Optional
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 98
Initialization Block
Initialization blocks can be used to initialize objects along with the constructors. An
initialization block is a block of statements enclosed inside a pair of braces. An
initialization block appears within the class declaration, but not inside methods or
constructors. It is executed as if it were placed at the beginning of every constructor
in the class.
public class Book {
private static int numOfObjects;
private String title;
private int id;
public Book(String title) {
numOfObjects++;
this.title = title;
}
public Book(int id) {
numOfObjects++;
this.id = id;
}
}
public class Book {
private static int numOfObjects;
private String title
private int id;
public Book(String title) {
this.title = title;
}
public Book(int id) {
this.id = id;
}
{
numOfObjects++;
}
}
Equivalent
Optional
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 99
Static Initialization Block
A static initialization block is much like a
nonstatic initialization block except that it is
declared static, can only refer to static members of
the class, and is invoked when the class is loaded.
The JVM loads a class when it is needed. A
superclass is loaded before its subclasses.
InitializationDemo Run
Optional
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 100
Inheriting GUI Components
Objective: Create a custom frame by
extending JFrame.
CustomFrame Run
Optional
GUI
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
ABSTRACT CLASSES AND INTERFACES
101
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 102
The abstract Modifier
The abstract class
– Cannot be instantiated
– Should be extended and implemented in
subclasses
The abstract method
– Method signature without
implementation
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 103
GeometricObject
-color: String
-filled: boolean
-dateCreated: java.util.Date
+GeometricObject()
+getColor(): String
+setColor(color: String): void
+isFilled(): boolean
+setFilled(filled: boolean): void
+getDateCreated(): java.util.Date
+toString(): String
The color of the object (default: white).
Indicates whether the object is filled with a color (default: false).
The date when the object was created.
Creates a GeometricObject.
Returns the color.
Sets a new color.
Returns the filled property.
Sets a new filled property.
Returns the dateCreated.
Returns a string representation of this object.
Circle
-radius: double
+Circle()
+Circle(radius: double)
+getRadius(): double
+setRadius(radius: double): void
+getArea(): double
+getPerimeter(): double
+getDiameter(): double
Rectangle
-width: double
-height: double
+Rectangle()
+Rectangle(width: double, height: double)
+getWidth(): double
+setWidth(width: double): void
+getHeight(): double
+setHeight(height: double): void
+getArea(): double
+getPerimeter(): double
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 104
Abstract Classes
GeometricObject
Circle
Rectangle
GeometricObject
-color: String
-filled: boolean
-dateCreated: java.util.Date
#GeometricObject()
+getColor(): String
+setColor(color: String): void
+isFilled(): boolean
+setFilled(filled: boolean): void
+getDateCreated(): java.util.Date
+toString(): String
+getArea(): double
+getPerimeter(): double
Circle
-radius: double
+Circle()
+Circle(radius: double)
+getRadius(): double
+setRadius(radius: double): void
+getDiameter(): double
Rectangle
-width: double
-height: double
+Rectangle()
+Rectangle(width: double, height: double)
+getWidth(): double
+setWidth(width: double): void
+getHeight(): double
+setHeight(height: double): void
The # sign indicates
protected modifer
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 105
NOTE
An abstract method cannot be contained in
a nonabstract class. If a subclass of an
abstract superclass does not implement all
the abstract methods, the subclass must be
declared abstract. In other words, in a
nonabstract subclass extended from an
abstract class, all the abstract methods
must be implemented, even if they are not
used in the subclass.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 106
NOTE
An abstract class cannot be instantiated
using the new operator, but you can still
define its constructors, which are invoked
in the constructors of its subclasses. For
instance, the constructors of
GeometricObject are invoked in the Circle
class and the Rectangle class.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 107
NOTE
A class that contains abstract methods
must be abstract. However, it is possible to
declare an abstract class that contains no
abstract methods. In this case, you cannot
create instances of the class using the new
operator. This class is used as a base class
for defining a new subclass.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 108
NOTE
A subclass can be abstract even if its
superclass is concrete. For example, the
Object class is concrete, but its subclasses,
such as GeometricObject, may be abstract.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 109
NOTE
A subclass can override a method from its
superclass to declare it abstract. This is
rare, but useful when the implementation
of the method in the superclass becomes
invalid in the subclass. In this case, the
subclass must be declared abstract.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 110
NOTE
You cannot create an instance from an
abstract class using the new operator, but
an abstract class can be used as a data
type. Therefore, the following statement,
which creates an array whose elements are
of GeometricObject type, is correct.
GeometricObject[] geo = new
GeometricObject[10];
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 111
Example: Using the GeometricObject
Class
Objective: This example creates two
geometric objects: a circle, and a rectangle,
invokes the equalArea method to check if the
two objects have equal area, and invokes the
displayGeometricObject method to display
the objects.
TestGeometricObject Run
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 112
The Abstract Calendar Class and Its
GregorianCalendar subclass
java.util.GregorianCalendar
+GregorianCalendar()
+GregorianCalendar(year: int,
month: int, dayOfMonth: int)
+GregorianCalendar(year: int,
month: int, dayOfMonth: int,
hour:int, minute: int, second: int)
Constructs a GregorianCalendar for the current time.
Constructs a GregorianCalendar for the specified year, month, and day of
month.
Constructs a GregorianCalendar for the specified year, month, day of
month, hour, minute, and second. The month parameter is 0-based, that
is, 0 is for January.
java.util.Calendar
#Calendar()
+get(field: int): int
+set(field: int, value: int): void
+set(year: int, month: int,
dayOfMonth: int): void
+getActualMaximum(field: int): int
+add(field: int, amount: int): void
+getTime(): java.util.Date
+setTime(date: java.util.Date): void
Constructs a default calendar.
Returns the value of the given calendar field.
Sets the given calendar to the specified value.
Sets the calendar with the specified year, month, and date. The month
parameter is 0-based, that is, 0 is for January.
Returns the maximum value that the specified calendar field could have.
Adds or subtracts the specified amount of time to the given calendar field.
Returns a Date object representing this calendar’s time value (million
second offset from the Unix epoch).
Sets this calendar’s time with the given Date object.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 113
The Abstract Calendar Class and Its
GregorianCalendar subclass
An instance of java.util.Date represents a
specific instant in time with millisecond
precision. java.util.Calendar is an abstract base
class for extracting detailed information such as
year, month, date, hour, minute and second from
a Date object. Subclasses of Calendar can
implement specific calendar systems such as
Gregorian calendar, Lunar Calendar and Jewish
calendar. Currently,
java.util.GregorianCalendar for the Gregorian
calendar is supported in the Java API.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 114
The GregorianCalendar Class
You can use new GregorianCalendar() to construct
a default GregorianCalendar with the current time
and use new GregorianCalendar(year, month, date)
to construct a GregorianCalendar with the specified
year, month, and date. The month parameter is 0-
based, i.e., 0 is for January.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 115
The get Method in Calendar Class
The get(int field) method defined in the Calendar class is
useful to extract the value for a given time field. The time
fields are defined as constants such as YEAR, MONTH,
DATE, HOUR (for the 12-hour clock), HOUR_OF_DAY
(for the 24-hour clock), MINUTE, SECOND,
DAY_OF_WEEK (the day number within the current week
with 1 for Sunday), DAY_OF_MONTH (same as the
DATE value), DAY_OF_YEAR (the day number within
the current year with 1 for the first day of the year),
WEEK_OF_MONTH (the week number within the current
month), and WEEK_OF_YEAR (the week number within
the current year). For example, the following code
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 116
Interfaces
An interface is a classlike construct that contains only
constants and abstract methods. In many ways, an interface
is similar to an abstract class, but an abstract class can
contain variables and concrete methods as well as
constants and abstract methods.
To distinguish an interface from a class, Java uses the
following syntax to declare an interface:
public interface InterfaceName {
constant declarations;
method signatures;
}
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 117
Interface is a Special Class
An interface is treated like a special class in Java.
Each interface is compiled into a separate bytecode
file, just like a regular class. Like an abstract class,
you cannot create an instance from an interface
using the new operator, but in most cases you can
use an interface more or less the same way you use
an abstract class. For example, you can use an
interface as a data type for a variable, as the result
of casting, and so on.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 118
Define Interfaces
Suppose you want to design a generic method to
find the larger of two objects. The objects can be
students, dates, or circles. Since compare methods
are different for different types of objects, you need
to define a generic compare method to determine
the order of the two objects. Then you can tailor
the method to compare students, dates, or circles.
For example, you can use student ID as the key for
comparing students, radius as the key for
comparing circles, and volume as the key for
comparing dates. You can use an interface to
define a generic compareTo method, as follows:
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 119
Example of an Interface
// This interface is defined in
// java.lang package
package java.lang;
public interface Comparable {
public int compareTo(Object o);
}
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 120
String and Date Classes
Many classes (e.g., String and Date) in the Java library
implement Comparable to define a natural order for the
objects. If you examine the source code of these classes,
you will see the keyword implements used in the classes,
as shown below:
public class String extends Object
implements Comparable {
// class body omitted
}
public class Date extends Object
implements Comparable {
// class body omitted
}
new String() instanceof String
new String() instanceof Comparable
new java.util.Date() instanceof java.util.Date
new java.util.Date() instanceof Comparable
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 121
Generic max Method
// Max.java: Find a maximum object
public class Max {
/** Return the maximum of two objects */
public static Object max
(Object o1, Object o2) {
if (((Comparable)o1).compareTo(o2) > 0)
return o1;
else
return o2;
}
}
(a)
// Max.java: Find a maximum object
public class Max {
/** Return the maximum of two objects */
public static Comparable max
(Comparable o1, Comparable o2) {
if (o1.compareTo(o2) > 0)
return o1;
else
return o2;
}
}
(b)
String s1 = "abcdef";
String s2 = "abcdee";
String s3 = (String)Max.max(s1, s2);
Date d1 = new Date();
Date d2 = new Date();
Date d3 = (Date)Max.max(d1, d2);
The return value from the max method is of the Comparable
type. So, you need to cast it to String or Date explicitly.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 122
Declaring Classes to Implement
Comparable
You cannot use the max method to find the larger of two instances of Rectangle,
because Rectangle does not implement Comparable. However, you can declare a
new rectangle class that implements Comparable. The instances of this new class
are comparable. Let this new class be named ComparableRectangle.
ComparableRectangle
ComparableRectangle rectangle1 = new ComparableRectangle(4, 5);
ComparableRectangle rectangle2 = new ComparableRectangle(3, 6);
System.out.println(Max.max(rectangle1, rectangle2));
Rectangle
-
GeometricObject
-
«interface»
java.lang.Comparable
+compareTo(o: Object): int
Notation:
The interface name and the
method names are italicized.
The dashed lines and hollow
triangles are used to point to
the interface.
ComparableRectangle
-
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 123
Interfaces vs. Abstract Classes
In an interface, the data must be constants; an abstract class can
have all types of data.
Each method in an interface has only a signature without
implementation; an abstract class can have concrete methods.
Variables Constructors Methods
Abstract
class
No restrictions Constructors are invoked by subclasses
through constructor chaining. An abstract
class cannot be instantiated using the
new operator.
No restrictions.
Interface All variables
must be public
static final
No constructors. An interface cannot be
instantiated using the new operator.
All methods must be
public abstract
instance methods
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 124
Interfaces vs. Abstract Classes,
cont.
All data fields are public final static and all methods are public
abstract in an interface. For this reason, these modifiers can be
omitted, as shown below:
public interface T1 {
public static final int K = 1;
public abstract void p();
}
Equivalent
public interface T1 {
int K = 1;
void p();
}
A constant defined in an interface can be accessed using syntax
InterfaceName.CONSTANT_NAME (e.g., T1.K).
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 125
Interfaces vs. Abstract Classes,
cont.
Object Class1
Interface1 Interface1_1
Interface1_2
Class2
Interface2_1
Interface2_2
Suppose that c is an instance of Class2. c is also an instance of Object, Class1,
Interface1, Interface1_1, Interface1_2, Interface2_1, and Interface2_2.
All classes share a single root, the Object class, but there is no single root for
interfaces. Like a class, an interface also defines a type. A variable of an interface
type can reference any instance of the class that implements the interface. If a class
extends an interface, this interface plays the same role as a superclass. You can use
an interface as a data type and cast a variable of an interface type to its subclass,
and vice versa.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 126
Caution: conflict interfaces
In rare occasions, a class may implement two interfaces
with conflict information (e.g., two same constants with
different values or two methods with same signature but
different return type). This type of errors will be detected
by the compiler.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 127
Whether to use an interface or a class?
Abstract classes and interfaces can both be used to model common
features. How do you decide whether to use an interface or a class?
In general, a strong is-a relationship that clearly describes a parent-
child relationship should be modeled using classes. For example, a
staff member is a person. So their relationship should be modeled
using class inheritance. A weak is-a relationship, also known as an
is-kind-of relationship, indicates that an object possesses a certain
property. A weak is-a relationship can be modeled using interfaces.
For example, all strings are comparable, so the String class
implements the Comparable interface. You can also use interfaces to
circumvent single inheritance restriction if multiple inheritance is
desired. In the case of multiple inheritance, you have to design one
as a superclass, and others as interface. See Chapter 10, “Object-
Oriented Modeling,” for more discussions.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 128
Creating Custom Interfaces
public interface Edible {
/** Describe how to eat */
public String howToEat();
}
class Animal {
}
class Chicken extends Animal
implements Edible {
public String howToEat() {
return "Fry it";
}
}
class Tiger extends Animal {
}
class abstract Fruit
implements Edible {
}
class Apple extends Fruit {
public String howToEat() {
return "Make apple cider";
}
}
class Orange extends Fruit {
public String howToEat() {
return "Make orange juice";
}
}
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 129
class Chicken extends Animal implements Edible, Comparable {
int weight;
public Chicken(int weight) {
this.weight = weight;
}
public String howToEat() {
return "Fry it";
}
public int compareTo(Object o) {
return weight – ((Chicken)o).weight;
}
}
Implements Multiple Interfaces
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 130
Creating Custom Interfaces, cont.
public interface Edible {
/** Describe how to eat */
public String howToEat();
}
public class TestEdible {
public static void main(String[] args) {
Object[] objects = {new Tiger(), new Chicken(), new Apple()};
for (int i = 0; i < objects.length; i++)
showObject(objects[i]);
}
public static void showObject(Object object) {
if (object instanceof Edible)
System.out.println(((Edible)object).howToEat());
}
}
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 131
The Cloneable Interfaces
package java.lang;
public interface Cloneable {
}
Marker Interface: An empty interface.
A marker interface does not contain constants or methods.
It is used to denote that a class possesses certain desirable
properties. A class that implements the Cloneable
interface is marked cloneable, and its objects can be
cloned using the clone() method defined in the Object
class.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 132
Examples
Many classes (e.g., Date and Calendar) in the Java library
implement Cloneable. Thus, the instances of these classes can be
cloned. For example, the following code
Calendar calendar = new GregorianCalendar(2003, 2, 1);
Calendar calendarCopy = (Calendar)calendar.clone();
System.out.println("calendar == calendarCopy is " +
(calendar == calendarCopy));
System.out.println("calendar.equals(calendarCopy) is " +
calendar.equals(calendarCopy));
displays
calendar == calendarCopy is false
calendar.equals(calendarCopy) is true
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 133
Implementing Cloneable Interface
To declare a custom class that implements the
Cloneable interface, the class must override the
clone() method in the Object class. The following code
declares a class named House that implements
Cloneable and Comparable.
House
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 134
Shallow vs. Deep Copy
house1: House
id = 1
area = 1750.50
whenBuilt
1
Memory
whenBuilt: Date
date object contents house2 = house1.clone()
1750.50
reference
house1: House
id = 1
area = 1750.50
whenBuilt
1
Memory
1750.50
reference
House house1 = new House(1, 1750.50);
House house2 = (House)house1.clone();
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 135
Wrapper Classes
Boolean
Character
Short
Byte
Integer
Long
Float
Double
Object
-
Double
-
Float
-
Long
-
Integer
-
Short
-
Byte
-
Character
-
Boolean
-
Number
-
Comparable
-
NOTE: (1) The wrapper classes do
not have no-arg constructors. (2)
The instances of all wrapper
classes are immutable, i.e., their
internal values cannot be changed
once the objects are created.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6
Object-Oriented Design
136
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 137
Software Development Process
Requirement
Specification
System
Analysis
System
Design
Testing
Implementation
Maintenance
Deployment
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 138
Requirement Specification
Requirement
Specification
System
Analysis
System
Design
Testing
Implementation
Maintenance
Deployment
A formal process that seeks to understand
the problem and document in detail what
the software system needs to do. This
phase involves close interaction between
users and designers.
Most of the examples in this book are simple,
and their requirements are clearly stated. In
the real world, however, problems are not
well defined. You need to study a problem
carefully to identify its requirements.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 139
System Analysis
Requirement
Specification
System
Analysis
System
Design
Testing
Implementation
Maintenance
Deployment
Seeks to analyze the business
process in terms of data flow, and
to identify the system’s input and
output.
Part of the analysis entails modeling
the system’s behavior. The model is
intended to capture the essential
elements of the system and to define
services to the system.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 140
System Design
Requirement
Specification
System
Analysis
System
Design
Testing
Implementation
Maintenance
Deployment
The process of designing the
system’s components.
This phase involves the use of many levels
of abstraction to decompose the problem into
manageable components, identify classes and
interfaces, and establish relationships among
the classes and interfaces.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 141
Implementation
Requirement
Specification
System
Analysis
System
Design
Testing
Implementation
Maintenance
Deployment
The process of translating the
system design into programs.
Separate programs are written for
each component and put to work
together.
This phase requires the use of a
programming language like Java.
The implementation involves
coding, testing, and debugging.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 142
Testing
Requirement
Specification
System
Analysis
System
Design
Testing
Implementation
Maintenance
Deployment
Ensures that the code meets the
requirements specification and
weeds out bugs.
An independent team of software
engineers not involved in the design
and implementation of the project
usually conducts such testing.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 143
Deployment
Requirement
Specification
System
Analysis
System
Design
Testing
Implementation
Maintenance
Deployment
Deployment makes the project
available for use.
For a Java applet, this means
installing it on a Web server; for a
Java application, installing it on the
client's computer.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 144
Maintenance
Requirement
Specification
System
Analysis
System
Design
Testing
Implementation
Maintenance
Deployment
Maintenance is concerned with
changing and improving the
product.
A software product must continue to
perform and improve in a changing
environment. This requires periodic
upgrades of the product to fix newly
discovered bugs and incorporate changes.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 145
Relationships among Classes
Association
Aggregation
Composition
Inheritance
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 146
Association
Association represents a general binary relationship that
describes an activity between two classes.
Student * 5..60
Take Teach
0..3 1
Teacher Faculty Course
public class Student {
/** Data fields */
private Course[]
courseList;
/** Constructors */
/** Methods */
}
public class Course {
/** Data fields */
private Student[]
classList;
private Faculty faculty;
/** Constructors */
/** Methods */
}
public class Faculty {
/** Data fields */
private Course[]
courseList;
/** Constructors */
/** Methods */
}
An association is usually represented as a data field in the class.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 147
Association Between Same Class
Association may exist between objects of the same class.
For example, a person may have a supervisor.
Person
Supervisor
1
1
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 148
Aggregation and Composition
Aggregation is a special form of association, which
represents an ownership relationship between two
classes. Aggregation models the has-a relationship. If
an object is exclusively owned by an aggregated object,
the relationship between the object and its aggregated
object is referred to as composition.
Name Address Person
Composition Aggregation
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 149
Representing Aggregation in
Classes
An aggregation relationship is usually represented as a
data field in the aggregated class.
public class Name {
/** Data fields */
/** Constructors */
/** Methods */
}
public class Person {
/** Data fields */
private Name name;
private Address address;
/** Constructors */
/** Methods */
}
public class Address {
/** Data fields */
/** Constructors */
/** Methods */
}
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 150
Inner Classes Translation
If Name or Address is used in the Person class only, they
can be declared as an inner class in Person. For example,
public class Person {
private Name name;
private Address address;
...
class Name {
...
}
class Address {
...
}
}
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 151
Inheritance
Inheritance models the is-an-extension-of
relationship between two classes.
Person Faculty
public class Faculty extends Person {
/** Data fields */
/** Constructors */
/** Methods */
}
(A) (B)
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 152
Weak Inheritance Relationship
A weak is-an-extension-of relationship can be represented using
interfaces. For example, the weak is-an-extension-of relationship
“students are comparable based on their grades” can be represented
by implementing the Comparable interface, as follows:
Person
Student
Comparable
public class Student extends Person
implements Comparable {
/** Data fields, Constructors, and */
/** Methods */
/** Implement the compareTo method */
public int compareTo(Object object) {
// ...
}
}
(A) (B)
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 153
Class Design
1. Identify classes for the system.
2. Describe attributes and methods in each
class.
3. Establish relationships among classes.
4. Create classes.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 154
Example 11.1 Borrowing Loans
Name Borrower Person Loan Address
Loan
Borrower
-loan: Loan
+Borrower()
+Borrower(name: Name, address: Address)
+getLoan(): Loan
+setLoan(loan: Loan): void
+toString(): String
Address
-street: String
-city: String
-state: String
-zip: String
+Address()
+Address(street: String, city: String,
state: String, zip: String)
+getStreet(): String
+getCity(): String
+getState(): String
+getZip(): String
+setStreet(street: String): void
+setCity(city: String): void
+setState(state: String): void
+setZip(zip: String): void
+getFullAddress(): String
Defined in
Example 6.7
Person
-name: Name
-address: Address
+Person()
+Person(name: Name, address: Address)
+getName(): Name
+seName(name: Name): void
+getAddress(): Address
+setAddress(address: Address): void
+toString(): String
Name
-firstName: String
-mi: char
-lastName: String
+Name()
+Name(firstName: String,
mi: char, lastName: String)
+getFirstName(): String
+getMi(): char
+getLastName(): String
+setFirstName(firstName:
String): void
+setMi(mi: char): void
+setLastName(lastName:
String): void
+getFullName(): String
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 155
Example 11.1 Borrowing Loans,
cont.
The following is a test program that uses
the classes Name, Person, Address,
Borrower, and Loan.
BorrowLoan Run
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 156
Example 11.2 The Rational Class
Rational Run TestRationalClass
1
1 Add, Subtract, Multiply, Divide
Rational
-numerator: long
-denominator: long
+Rational()
+Rational(numerator: long, denominator: long)
+getNumerator(): long
+getDenominator(): long
+add(secondRational: Rational): Rational
+multiply(secondRational: Rational): Rational
+subtract(secondRational: Rational): Rational
+divide(secondRational: Rational): Rational
+toString(): String
-gcd(n: long, d: long): long
java.lang.Number
+byteValue(): byte
+shortValue(): short
+intValue(): int
+longVlaue(): long
+floatValue(): float
+doubleValue():double
java.lang.Comparable
compareTo(Object): int
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 157
Class Design Guidelines
Designing a Single Class.
Using Modifiers public, protected, private
and static
Using Inheritance or Aggregation
Using Interfaces or Abstract Classes
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 158
Designing a Class
A class should describe a single entity or a set of
similar operations. A single entity with too many
responsibilities can be broken into several classes
to separate responsibilities. The String class,
StringBuffer class, and StringTokenizer class all
deal with strings, for example, but have different
responsibilities.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 159
Designing a Class, cont.
Classes are usually designed for use by many
different customers. To make a class useful in a
wide range of applications, the class should
provide a variety of ways for customization
through properties and methods.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 160
Designing a Class, cont.
Classes are designed for reuse. Users can
incorporate classes in many different combinations,
orders, and environments. Therefore, you should
design a class that imposes no restrictions on what
or when the user can do with it, design the properties
to ensure that the user can set properties in any
order, with any combination of values, and design
methods to function independently of their order of
occurrence.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 161
Designing a Class, cont.
Provide a public no-arg constructor and override the
equals method and the toString method defined in
the Object class whenever possible.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 162
Designing a Class, cont.
Follow standard Java programming style and
naming conventions. Choose informative
names for classes, data fields, and methods.
Always place the data declaration before the
constructor, and place constructors before
methods. Always provide a constructor and
initialize variables to avoid programming
errors.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 163
Using Visibility Modifiers
Each class can present two contracts – one for the users
of the class and one for the extenders of the class. Make
the fields private and accessor methods public if they are
intended for the users of the class. Make the fields or
method protected if they are intended for extenders of the
class. The contract for the extenders encompasses the
contract for the users. The extended class may increase
the visibility of an instance method from protected to
public, or change its implementation, but you should
never change the implementation in a way that violates
that contract.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 164
Using Visibility Modifiers,
cont.
A class should use the private modifier to hide its
data from direct access by clients. You can use get
methods and set methods to provide users with
access to the private data, but only to private data
you want the user to see or to modify. A class
should also hide methods not intended for client use.
The gcd method in the Rational class in Example
11.2, “The Rational Class,” is private, for example,
because it is only for internal use within the class.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 165
Using the static Modifier
A property that is shared by all the
instances of the class should be declared
as a static property.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 166
Using Inheritance or
Aggregation
In general, the difference between inheritance
and aggregation is the difference between the
is-an-extension-of relationship and the has-a
relationship. For example, an apple is fruit;
thus, you would use inheritance to model the
relationship between the classes Apple and
Fruit. A person has a name; thus, you would
use aggregation to model the relationship
between the classes Person and Name.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 167
Using Inheritance or
Aggregation, cont.
Sometimes, the choice between inheritance
and aggregation is not obvious. For example,
you have used inheritance to model the
relationship between the classes Circle and
Cylinder. One could argue that a cylinder
consists of circles; thus, you might use
aggregation to define the Cylinder class as
follows:
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 168
Using Inheritance or
Composition, cont.
public class Cylinder {
private Circle circle;
/** Constructors */
/** Methods */
}
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 169
Using Inheritance or
Aggregation, cont.
Both designs are fine. Which one is
preferred? If polymorphism is desirable, you
need to use the inheritance design. If you
don’t care about polymorphism, the
aggregation design gives more flexibility
because the classes are less dependent using
aggregation than using inheritance.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 170
Using Interfaces or Abstract
Classes
Both interfaces and abstract classes can be
used to generalize common features. How do
you decide whether to use an interface or a
class? In general, a strong is-an-extension-of
relationship that clearly describes a parent-
child relationship should be modeled using
classes.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 171
Using Interfaces or Abstract
Classes, cont.
For example, since an orange is a fruit, their relationship
should be modeled using class inheritance. A weak is-an-
extension-of relationship, also known as an is-kind-of
relationship, indicates that an object possesses a certain
property. A weak is-an-extension-of relationship can be
modeled using interfaces. For example, all strings are
comparable, so the String class implements the
Comparable interface. A circle or a rectangle is a
geometric object, for example, so Circle can be designed
as a subclass of GeometricObject. Circles are different
and comparable based on their radius, for example, so
Circle can implement the Comparable interface.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 172
Using Interfaces or Abstract
Classes, cont.
Interfaces are more flexible than abstract classes,
because a subclass can extend only one superclass,
but implement any number of interfaces. However,
interfaces cannot contain concrete methods. You
can combine the virtues of interfaces and abstract
classes by creating an interface with a companion
abstract class that implements the interface. So you
can use the interface or its companion class
whichever is more convenient.
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 173
Sequence diagrams
Sequence diagrams describe interactions among
objects by depicting the time ordering of method
invocations.
anObject: TheClass Class role
Method Invocation
Activation
anotherObject: TheOtherClass
Method Invocation
anotherMethod()
aMethod()
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 174
Sequence diagrams, cont.
name: Name : BorrowLoan address: Address loan: Loan borrower: Borrower
setFirstName
setMi
setLastName
setStreet
setCity
setState
setZip
setAnnualInterestRate
setNumOfYears
setLoanAmount
setName
setAddress
setLoan
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 175
Statechart diagrams
Statechart diagrams describe flow of control of
the object.
Indicate
Initial State
Transition
State1
State2
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 176
Statechart diagrams, cont.
Class Loaded
JVM loads the
class for the object
Use the new operator
to create the object
Object Created
Invoke the finalize
method on the object
Object Destroyed
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 177
Supplement P: Designing Generic
Matrix Classes
Objective: This example gives a generic class
for matrix arithmetic. This class implements
matrix addition and multiplication common for
all types of matrices.
GenericMatrix
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 178
Example 11.3, cont.
GenericMatrix
-matrix: Object[][]
#GenericMatrix(matrix: Object[][])
+getMatrix(): Object[][]
+setMatrix(matrix: Object[][]): void
+addMatrix(secondMatrix: Object[][]): Object[][]
+multiplyMatrix(secondMatrix: Object[][]): Object[][]
+printResult(m1: GenericMatrix, m2: GenericMatrix,
m3: GenericMatrix, op: char): void
#createGenericMatrix():GenericMatrix
#add(o1: Object, o2: Object): Object
#multiply(o1: Object, o2: Object): Object
#zero():Object
IntegerMatrix
RationalMatrix
Liang, Introduction to Java Programming, Sixth Edition, (c) 2005 Pearson Education, Inc. All
rights reserved. 0-13-148952-6 179
Example 11.3, cont.
Objective: This example gives two programs that
utilize the GenericMatrix class for integer matrix
arithmetic and rational matrix arithmetic.
TestIntegerMatrix Run
TestRationalMatrix Run RationalMatrix
IntegerMatrix
Các file đính kèm theo tài liệu này:
- advanced_programminglanguage_nguyencaodat_c2_8173_1811634.pdf