Chapter 11 - Computer and Information Science

advertisement
1
Chapter 11 Abstract Classes and
Interfaces
2
Abstract method
• New modifier for class and method: abstract
• An abstract method has no body
• Compare: abstract and concrete.
Abstract Classes and Abstract Methods
G eom etricO bject
3
A b stra ct cla ss
-c olo r: Strin g
GeometricObject
-filled : bo olea n
T he # sig n in dica tes
pro te c te d m o difer
-da teC r ea ted: ja va .u til.D a te
# G eo m etr icO bje ct()
Circle
+ ge tC o lor (): Strin g
+ setC olor( co lor : S tring) : vo id
+ isFille d(): b o olea n
+ setF ille d( fille d: b o olea n): v oid
Rectangle
+ ge tD a te C r ea te d() : ja va .u til.D a te
+ toS tring() : String
+ g e tA re a (): d o u b le
A b stra ct m eth od s
+ g e tPe rim e te r (): d o u b le
R ectangle
C ircle
-ra diu s: dou ble
+ C ircle()
M e th o d s ge tA r ea a n d g etP er im e te r a r e ov errid d en in
C irc le a n d R e cta ng le . O v erridd e n m eth od s a r e
ge n era lly o m itte d in the U M L dia gra m fo r su b cla sse s.
-w idth: d ou b le
-h eig ht: dou ble
+ C ircle(ra diu s: d ou ble)
+ R e cta n gle()
+ ge tR a diu s() : dou ble
+ R e cta n gle( w idth: d ou b le , he ig ht: dou ble)
+ setR a diu s( ra diu s: d ou ble) : vo id
+ ge tW idth(): d ou b le
+ ge tD ia m e ter (): d ou ble
+ setW idth( w idth: d ou b le ): vo id
+ ge tH e ig ht() : dou ble
+ setH eigh t(h eig ht: d ou ble) : vo id
TestGometricObject
Run
abstract method in abstract class
 An abstract method -> must be abstract class.
 Subclass of an abstract superclass does not
override all abstract methods -> must be abstract.
A class can be abstract with no abstract methods.
4
object cannot be created from abstract
class
Can have variable of abstract class type
An abstract class cannot be instantiated
using the new operator
 Can have constructors - invoked by
subclasses.
5
superclass of abstract class may be
concrete
 If a class is concrete, does that mean all
subclasses are concrete?
NO!
Object class is concrete, but we can still
have abstract classes.
6
concrete method overridden to be
abstract
A subclass can override a concrete method
from its (perhaps concrete) superclass to
declare it abstract.
 Rare, but useful when superclass
implementation becomes invalid in the
subclass.
7
Interfaces
What is an interface?
Why is an interface useful?
How do you define an interface?
How do you use an interface?
8
9
What is an interface?
Why is an interface useful?
 like a class, but contains only constants and
abstract methods
 In many ways, similar to an abstract class
 purpose: specify behavior for objects
 For example, specify that the objects are
 comparable
 edible
 cloneable
Define an Interface
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();
}
Interface is a Special Class
11
 Treated like special class in Java
 Each interface is compiled into a separate bytecode
file
 cannot create an instance from an interface using
the new operator
can use interface as data type for a variable
12
Omitting Modifiers in Interfaces
Fields are public final static
Methods are public abstract in an interface.
Thus, these modifiers can be omitted
public interface T1 {
public static final int K = 1;
Eq uiva le nt
public interface T1 {
int K = 1;
void p();
public abstract void p();
}
}
A constant defined in an interface can be accessed using syntax
InterfaceName.CONSTANT_NAME (e.g., T1.K).
13
Example: The Comparable
Interface
// This interface is defined in
// java.lang package
package java.lang;
public interface Comparable {
public int compareTo(Object o);
}
String and Date Classes
14
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
new
new
new
String() instanceof String
String() instanceof Comparable
java.util.Date() instanceof java.util.Date
java.util.Date() instanceof Comparable
15
Generic max Method
// Max.java: Find a maximum object
public class Max {
/** Return the maximum of two objects */
public static Comparable max
( C o m p a r a b l e o 1 , C o m p a r a b l e o 2) {
if (o1.compareTo(o2) > 0)
return o1;
else
return o2;
}
}
(a)
String s1 = "abcdef";
String s2 = "abcdee";
String s3 = (String)Max.max(s1, s2);
// Max.java: Find a maximum object
public class Max {
/** Return the maximum of two objects */
public static Object max
( O b j e c t o 1 , O b j e c t o 2) {
i f ( ( ( C o m p a r a b l e ) o 1) . c o m p a r e T o ( o 2 ) > 0 )
return o1;
else
return o2;
}
}
(b)
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.
16
Declaring Classes to Implement Comparable
N o ta tio n :
T h e in terfa ce n a m e a nd th e
m eth o d n a m es a re ita licized .
T h e d a sh ed lin es an d ho llo w
tria n g les a re u sed to p o in t to
th e in terfa ce.
«in terface»
G eo m etricO b ject
ja va .la ng .C o m p a ra b le
R ectan gle
+ co m p a reT o (o : O b ject): in t
C o m p arab leR ecta ng le
-
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));
The Cloneable Interfaces
Marker Interface: An empty interface.
A marker interface does not contain constants or
methods.
Used to denote that a class possesses certain 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.
package java.lang;
public interface Cloneable {
}
17
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
18
19
Shallow vs. Deep Copy
House house1 = new House(1, 1750.50);
House house2 = (House)house1.clone();
ho use1 : H o use
id = 1
M em ory
1
area = 1 750 .5 0
1 750 .5 0
w h en B u ilt
referen ce
d ate ob ject con tents
h ou se2 = h ou se1.clon e()
ho use1 : H o use
id = 1
w h en B u ilt: D ate
M em ory
1
area = 1 750 .5 0
1 750 .5 0
w h en B u ilt
referen ce
20
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
Interfaces vs. Abstract Classes, cont.
Only 1 base class, can implement multiple interfaces.
Interfaces can be used for multiple inheritance.
In terfa ce1 _ 2
In terfa ce1 _ 1
O b ject
In terfa ce2 _ 2
In terfa ce1
C la ss1
In terfa ce2 _ 1
C lass2
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.
21
Caution: conflict interfaces
22
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.
23
Wrapper Classes
• Boolean

• Character

Integer
Long
• Short

Float
• Byte

Double
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.
java.lang.O b ject
ja va .la ng .C o m p a ra b le
-
-
N u m b er
C haracter
-
-
D o ub le
-
F lo at
-
Long
-
Integer
-
S ho rt
-
B yte
-
B o o lean
-
The toString, equals, and hashCode
Methods
Each wrapper class overrides the
toString, equals, and hashCode methods
defined in the Object class. Since all the
numeric wrapper classes and the
Character class implement the
Comparable interface, the compareTo
method is implemented in these classes.
24
The Number Class
25
•Each numeric wrapper class extends the abstract
Number class
▫Contains methods doubleValue, floatValue,
intValue, longValue, shortValue, and byteValue.
•These methods “convert” objects into primitive
type values.
•doubleValue, floatValue, intValue, longValue are
abstract.
•byteValue and shortValue are not abstract
▫return (byte)intValue() and (short)intValue(),
respectively.
•Is Number class concrete or abstract?
The Integer and Double Classes
ja va .la ng .N u m b er
+ b yteV alu e(): b yte
+ sh ortV alu e(): sh ort
+ in tV a lue(): int
+ lo ng V lau e(): long
+ floa tV alue(): floa t
+ do ubleV a lu e():dou ble
ja va .la ng .C o m p a ra b le
+ co m pa reTo (o : O b ject): in t
java.lan g.In teger
-valu e: in t
+ M A X _ V A L U E : in t
+ M IN _ V A L U E : in t
+ In teger(valu e: in t)
+ In teger(s: S trin g)
+ valu eO f(s: S trin g): In teg er
+ valu eO f(s: S trin g, rad ix: in t): In teg er
+ p arseIn t(s: S trin g): int
+ p arseIn t(s: S trin g, rad ix: in t): int
java.lan g.D o u b le
-valu e: d ou b le
+ M A X _ V A L U E : d ou b le
+ M IN _ V A L U E : d ou b le
+ D ou b le(valu e: d ou b le)
+ D ou b le(s: S trin g)
+ valu eO f(s: S trin g): D ou b le
+ valu eO f(s: S trin g, rad ix: in t): D oub le
+ p arseD oub le(s: S trin g): d ou b le
+ p arseD oub le (s: S trin g, rad ix: int): dou b le
26
27
The Integer Class
and the Double Class
• Constructors
• Class Constants MAX_VALUE, MIN_VALUE
• Conversion Methods
28
Numeric Wrapper Class Constructors
You can construct a wrapper object either from a
primitive data type value or from a string
representing the numeric value.
Constructors for Integer:
public Integer(int value)
public Integer(String s)
Constructors for Double are
public Double(double value)
public Double(String s)
29
Numeric Wrapper Class Constants
•Each numerical wrapper class has the constants
MAX_VALUE and MIN_VALUE.
•MAX_VALUE represents the maximum value of
the corresponding primitive data type.
•For Byte, Short, Integer, and Long, MIN_VALUE
represents the minimum byte, short, int, and long
values.
•For Float and Double, MIN_VALUE represents
the minimum positive float and double values.
30
Conversion Methods
•Each numeric wrapper class implements abstract
methods which are defined in the Number class.
▫doubleValue
▫floatValue,
▫intValue,
▫longValue,
▫shortValue,
•These methods “convert” objects into primitive type
values.
31
The Static valueOf Methods
•The numeric wrapper classes have a
class method, valueOf(String s).
•Creates a new object with the value
represented by the String.
•For example:
Double doubleObject = Double.valueOf("12.4");
Integer integerObject = Integer.valueOf("12");
The Methods for Parsing Strings into
Numbers
•Each numeric wrapper class has
overloaded parsing methods to parse a
numeric string into a primitive numeric
value.
•parseInt in the Integer class parses a
numeric string into an int value.
•parseDouble in the Double class parses
a numeric string into a double value.
32
33
Sorting an Array of Objects
Objective: The example presents a generic method
for sorting an array of objects. The objects are
instances of the Comparable interface and they are
compared using the compareTo method.
GenericSort
Run
34
TIP
Java provides a static sort method for sorting an
array of Object in the java.util.Arrays class. So you
can use the following code to sort arrays in this
example:
java.util.Arrays.sort(intArray);
java.util.Arrays.sort(doubleArray);
java.util.Arrays.sort(charArray);
java.util.Arrays.sort(stringArray);
35
NOTE
Arrays are objects. An array is an instance of the
Object class. Furthermore, if A is a subclass of B,
every instance of A[] is an instance of B[]. Therefore,
the following statements are all true:
new int[10] instanceof Object
new GregorianCalendar[10] instanceof Calendar[];
new Calendar[10] instanceof Object[]
new Calendar[10] instanceof Object
36
CAUTION
•
An int value can be assigned to a double type
variable.
•
Yet int[] and double[] are two incompatible
types.
•
Therefore, you cannot assign an int[] array to a
variable of double[] or Object[] type.
37
Automatic Conversion Between Primitive
Types and Wrapper Class Types
JDK 1.5 allows primitive type and wrapper classes to be converted automatically. For
example, the following statement in (a) can be simplified as in (b):
Integer[] intArray = {new Integer(2),
new Integer(4), new Integer(3)};
(a)
E q uiva le nt
Integer[] intArray = {2, 4, 3};
N ew JD K 1.5 boxing
Integer[] intArray = {1, 2, 3};
System.out.println(intArray[0] + intArray[1] + intArray[2]);
Unboxing
(b)
38
BigInteger and BigDecimal
 For computation with very large integers or high
precision floating-point values, use the BigInteger
and BigDecimal classes in the java.math package.
 Both are immutable.
 Both extend the Number class and implement the
Comparable interface.
39
BigInteger and BigDecimal
BigInteger a = new
BigInteger("9223372036854775807");
BigInteger b = new BigInteger("2");
BigInteger c = a.multiply(b); // 9223372036854775807 *
2
System.out.println(c);
LargeFactorial
Run
BigDecimal a = new BigDecimal(1.0);
BigDecimal b = new BigDecimal(3);
BigDecimal c = a.divide(b, 20, BigDecimal.ROUND_UP);
System.out.println(c);
Download