Chapter 9: Objects and Classes

advertisement
1








To design and use abstract classes
To process a calendar using the Calendar and GregorianCalendar
classes
To specify behavior for objects using interfaces
To define interfaces and declare classes that implement interfaces
To define a natural order using the Comparable interface
To enable objects to listen for action events using the ActionListener
interface
To make objects cloneable using the Cloneable interface
To explore the similarities and differences between an abstract class
and an interface
2
GeometricObject
Abstract class
-color: String
GeometricObject
-filled: boolean
The # sign indicates
protected modifer
-dateCreated: java.util.Date
#GeometricObject()
Circle
+getColor(): String
+setColor(color: String): void
+isFilled(): boolean
+setFilled(filled: boolean): void
Rectangle
+getDateCreated(): java.util.Date
+toString(): String
Abstract methods
+getArea(): double
+getPerimeter(): double
Methods getArea and getPerimeter are overridden in
Circle and Rectangle. Overridden methods are
generally omitted in the UML diagram for subclasses.
Rectangle
Circle
-radius: double
-width: double
+Circle()
-height: double
+Circle(radius: double)
+Rectangle()
+getRadius(): double
+Rectangle(width: double, height: double)
+setRadius(radius: double): void
+getWidth(): double
+getDiameter(): double
+setWidth(width: double): void
+getHeight(): double
TestGometricObject
Run
+setHeight(height: double): void
3
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.
4
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.
5
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.
6
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.
7
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.
What is an interface?
Why is an interface useful?
How do you define an interface?
How do you use an interface?
9
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 the intent of
an interface is to specify behavior for
objects. For example, you can specify that
the objects are comparable, edible,
cloneable using appropriate interfaces.
10
To distinguish an interface from a class, Java uses the
following syntax to declare an interface:
public interface InterfaceName {
constant declarations;
method signatures;
}
Example:
public interface Edible {
/** Describe how to eat */
public abstract String howToEat();
}
11
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.
12
You can now use the Edible interface to specify
whether an object is edible. This is accomplished
by letting the class for the object implement this
interface using the implements keyword. For
example, the classes Chicken and Fruit in Listing
implement the Edible interface.
Edible
TestEdible
Run
13
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).
14
// This interface is defined in
// java.lang package
package java.lang;
public interface Comparable {
public int compareTo(Object o);
}
15
// 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;
}
}
(a)
Interface used as data
type, the passed in
parameters must be
classes that implement
the interface. The
invoked methods must
be defined in the
interface.
String s1 = "abcdef";
String s2 = "abcdee";
String s3 = (String)Max.max(s1, s2);
The return value from the max method is of the Comparable
type. So, you need to cast it to String explicitly.
16
Notation:
The interface name and the
method names are italicized.
The dashed lines and hollow
triangles are used to point to
the interface.
GeometricObject
Rectangle
«interface»
java.lang.Comparable
+compareTo(o: Object): int
ComparableRectangle
-
ComparableRectangle
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 rectangle1 = new ComparableRectangle(4, 5);
ComparableRectangle rectangle2 = new ComparableRectangle(3, 6);
System.out.println(Max.max(rectangle1, rectangle2));
17
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.
package java.lang;
public interface Cloneable {
}
18
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
19
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
20
House house1 = new House(1, 1750.50);
House house2 = (House)house1.clone();
house1: House
id = 1
Memory
area = 1750.50
1
1750.50
whenBuilt
reference
date object contents
house2 = house1.clone()
house1: House
id = 1
whenBuilt: Date
Memory
area = 1750.50
1
1750.50
whenBuilt
reference
21
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
methods
22
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
implements 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.
Interface1_2
Interface1_1
Object
Interface2_2
Interface1
Class1
Interface2_1
Class2
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.
23
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 or behavior. A weak is-a relationship can be
modeled using interfaces. For example, all strings are
comparable, so the String class implements the
Comparable interface.
24












Indicate true or false for the following statements:
1.An abstract class can have instances created using the constructor of the
abstract class
2. An abstract class can be extended.
3. An interface can be a separate unit and can be compiled into a
bytecode file.
4
A subclass of a non-abstract superclass cannot be abstract.
5
A subclass cannot override a concrete method in a superclass to
declare it abstract.

6. An abstract method must be non-static

7 An interface can have static methods.

8 An interface can extend one or more interfaces.

9. A constant defined in the interface must be final and static.
25















Indicate true or false for the following statements:
1.An abstract class can have instances created using the constructor of the abstract
class.
Answer: No, but an instance of its concrete subclass is also an instance of the parent
abstract class. You cannot create an object using the constructor of the abstract class.
However, you can create an object using a concrete subclass of the abstract class. This
object is an instance of the subclass and it is also an instance of the abstract class.
2.An abstract class can be extended.
Answer: True
3.An interface can be a separate unit and can be compiled into a bytecode file.
Answer: True
4 . A subclass of a non-abstract superclass cannot be abstract.
Answer: False
5 A subclass cannot override a concrete method in a superclass to declare it abstract.
Answer: False, This is rare, but useful when the implementation of the method in the
superclass becomes invalid in the subclass. In this case, the subclass method must be
declared abstract.


6.An abstract method must be non-static
Answer: True


7 An interface can have static methods.
Answer: False


8 An interface can extend one or more interfaces.
Answer: True


9. A constant defined in the interface must be final and static.
Answer: True
26
1. Rewrite the house class to perform a deep copy on
the whenBuilt field.
2. The octagon class to extends GeometricObject class
and implements the Comparable and Cloneable
interface. Assume that all eight sides of the octagon
are of equal size. The area can be computed using
the following formula: area=(2+4/sqrt(2))side*side.
Draw the UML diagram that involves Octagon,
GeometricObject, Comparable, and Cloneable.
Write a test program that creates an Octagon object
with side value 5 and display the area and perimeter.
create new object using the clone method and
compare the two objects using the compareTo
method.
27
28
Download