Você está na página 1de 56

Page 1 of 56

Chapter 6. Object-oriented Programming


Exam Objectives

!
" !

Supplementary Objectives

$ #
# #
%
&&'(

$ this() super()

# #

) %
* (# instanceof

$ !

6.1 Single Implementation Inheritance


& &&'# +
, % ! # #
( % ! # #
( # #

+ - # , % #
( % ./# /00( +
+
% , , ! super(#
# #
% ./# /00( +

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hhD3DA.htm 6/16/2006


Page 2 of 56

% 1, .2(

extends

+ extends
# java.lang.Object
Light %
2( 1, .2 3 1,
.2# TubeLight %
/( , extends
Light % # #
Object ( 4 Light
TubeLight#

'
indicator Light # ,

$ #
# # % 56# 207( 3 1,
.2#
private 4
! ! #
!

% .0# /50( 8 ! % 9/# 002(


#

class Light { // (1)


// Instance fields
int noOfWatts; // wattage
private boolean indicator; // on or off
protected String location; // placement

// Static fields
private static int counter; // no. of Light objects created

// Constructor
Light() {
noOfWatts = 50;
indicator = true;
location = "X";
counter++;
}

// Instance methods
public void switchOn() { indicator = true; }
public void switchOff() { indicator = false; }
public boolean isOn() { return indicator; }
private void printLocation() {
System.out.println("Location: " + location);
}

// Static methods
public static void writeCount() {

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hhD3DA.htm 6/16/2006


Page 3 of 56

System.out.println("Number of lights: " + counter);


}
//...
}

class TubeLight extends Light { // (2) Subclass uses the extends clause.
// Instance fields
private int tubeLength = 54;
private int colorNo = 10;

// Instance methods
public int getTubeLength() { return tubeLength; }

public void printInfo() {


System.out.println("Tube length: " + getTubeLength());
System.out.println("Color number: " + colorNo);
System.out.println("Wattage: " + noOfWatts); // Inherited.
// System.out.println("Indicator: " + indicator); // Not Inherited.
System.out.println("Indicator: " + isOn()); // Inherited.
System.out.println("Location: " + location); // Inherited.
// printLocation(); // Not Inherited.
// System.out.println("Counter: " + counter); // Not Inherited.
writeCount(); // Inherited.
}
// ...
}

public class Utility { // (3)


public static void main(String[] args) {
new TubeLight().printInfo();
}
}

& :

Tube length: 54
Color number: 10
Wattage: 50
Indicator: true
Location: X
Number of lights: 1

3 - , " #
!
#
% (
; #
; # 8
< .2
Light# # 8
java.lang.Object - #
# , Object # % (

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hhD3DA.htm 6/16/2006


Page 4 of 56

+ % (

+ = 3 TubeLight
Light 3 TubeLight
Light : B ,
A, C# , B# A B 3
SpotLightBulb Light
: LightBulb TubeLight

#
% ! (
% ! 3 Light :
%
noOfWatts(# %
indicator(# String
% location( + - #
+
;

+ .9

Object-oriented Programming Concepts

, &&' # =

< ./ String Object


3 String 1, ./ ) , main()
# String %
2( :stringRef
String objRef Object ! main()
&&'

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hhD3DA.htm 6/16/2006


Page 5 of 56

// String class is a subclass of Object class


class Client {
public static void main(String[] args) {

String stringRef = new String("Java"); // (1)

System.out.println("(2): " + stringRef.getClass()); // (2)


System.out.println("(3): " + stringRef.length()); // (3)
Object objRef = stringRef; // (4)
// System.out.println("(5): " + objRef.length()); // (5) Not OK.
System.out.println("(6): " + objRef.equals("Java")); // (6)
System.out.println("(7): " + objRef.getClass()); // (7)

stringRef = (String) objRef; // (8)


System.out.println("(9): " + stringRef.equals("C++")); // (9)
}
}

& :

(2): class java.lang.String


(3): 4
(6): true
(7): class java.lang.String
(9): false

! String Object

Inheriting from the Superclass

String getClass() Object 3


String ! String
String + 1, ./#
%
/(

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hhD3DA.htm 6/16/2006


Page 6 of 56

System.out.println("(2): " + stringRef.getClass()); // (2)

Extending the Superclass

String length()# Object#


, + 1, ./#
String %
0(

System.out.println("(3): " + stringRef.length()); // (3)

Upcasting

3
#
% ..# /.>( + 1, ./# %5(#
stringRef objRef

Object objRef = stringRef; // (4)

String &
! , String objRef#
%
?(

System.out.println("(5): " + objRef.length()); // (5) Not OK.

@ # ! ! objRef
+ ! 3 Object
length()# length() %
?(

Method Overriding

+ %
?(# equals() %
.(
objRef ! Object
equals

System.out.println("(6): " + objRef.equals("Java")); // (6)

A String % #
( % ./#
/00(

Polymorphism and Dynamic Method Binding

equals() %
.(# objRef,
! equals() Object !

!
.7
!

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hhD3DA.htm 6/16/2006


Page 7 of 56

$ , # objRef String
%
.(# equals() String , #
Object

%
7(# getClass() !
objRef# Object getClass

System.out.println("(7): " + objRef.getClass()); // (7)

+ # , # objRef
String %
7( ) !
getClass() getClass() String #
getClass() Object ,

Downcasting

; %
..# /.>( 1, ./
# = ,

stringRef = (String) objRef; // (8)


System.out.println("(9): " + stringRef.equals("C++")); // (9)

3 %
9(# objRef Object#
stringRef + objRef
String # #
stringRef %9( stringRef
! equals() String # %
6( A # equals()
String ,

,
@ # +# #
objRef Object
Object# String +
# ClassCastException instanceof %
..# /.5(

Review Questions

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hhD3DA.htm 6/16/2006


Page 8 of 56

+ - extends

abstract abstract

3 final abstract

3 private#
public

1 - public equals

1 - public length

3 ,

3 final ,

6.2 Overriding and Hiding Members


Instance Method Overriding
$ #
! #
,
#
:

% #
(

final
% 0//# 65( 3 * final
#

#
% 56# 207(

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hhD3DA.htm 6/16/2006


Page 9 of 56

# ,
% ( throws
% ?6# />2(

= #
% .5# /?2(

+ 1, .0# getBill() %?( TubeLight


%/( Light
, %ZeroHoursException(
%, Invalid HoursException
NegativeHoursException ZeroHoursException(
%
public( %
protected(
final + getBill()
TubeLight %
2/( %
20(
# %
?( , + getBill
() Light %
25(#
%
/( ,

" #$ %#$ %

// Exceptions
class InvalidHoursException extends Exception {}
class NegativeHoursException extends InvalidHoursException {}
class ZeroHoursException extends InvalidHoursException {}
class Light {

protected String billType = "Small bill"; // (1)

protected double getBill(int noOfHours)


throws InvalidHoursException { // (2)
if (noOfHours < 0)
throw new NegativeHoursException();
double smallAmount = 10.0,
smallBill = smallAmount * noOfHours;
System.out.println(billType + ": " + smallBill);
return smallBill;
}

public static void printBillType() { // (3)


System.out.println("Small bill");
}

class TubeLight extends Light {

public static String billType = "Large bill"; // (4) Hiding static field.

public double getBill(final int noOfHours)


throws ZeroHoursException { // (5) Overriding instance method.
if (noOfHours == 0)
throw new ZeroHoursException();
double largeAmount = 100.0,
largeBill = largeAmount * noOfHours;
System.out.println(billType + ": " + largeBill);

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hhD3DA.htm 6/16/2006


Page 10 of 56

return largeBill;
}

public static void printBillType() { // (6) Hiding static method.


System.out.println(billType);
}

public double getBill() { // (7) Overloading method.


System.out.println("No bill");
return 0.0;
}
}

public class Client {


public static void main(String[] args)
throws InvalidHoursException { // (8)

TubeLight tubeLight = new TubeLight(); // (9)


Light light1 = tubeLight; // (10) Aliases.
Light light2 = new Light(); // (11)

System.out.println("Invoke overridden instance method:");


tubeLight.getBill(5); // (12) Invokes method at (5)
light1.getBill(5); // (13) Invokes method at (5)
light2.getBill(5); // (14) Invokes method at (2)
System.out.println("Access hidden field:");
System.out.println(tubeLight.billType); // (15) Accesses field at (4)
System.out.println(light1.billType); // (16) Accesses field at (1)
System.out.println(light2.billType); // (17) Accesses field at (1)

System.out.println("Invoke hidden static method:");


tubeLight.printBillType(); // (18) Invokes method at (6)
light1.printBillType(); // (19) Invokes method at (3)
light2.printBillType(); // (20) Invokes method at (3)

System.out.println("Invoke overloaded method:");


tubeLight.getBill(); // (21) Invokes method at (7)
}
}

& :

Invoke overridden instance method:


Large bill: 500.0
Large bill: 500.0
Small bill: 50.0
Access hidden field:
Large bill
Small bill
Small bill
Invoke hidden static method:
Large bill
Small bill
Small bill
Invoke overloaded method:
No bill

3 ! super !
% /09(

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hhD3DA.htm 6/16/2006


Page 11 of 56

3 static
3 #
! @ #
static % (

3 final final 3
final @ # abstract
= #

3 private
" # @ #
#

Field Hiding
3 #
+ #
" #
; ! super #
3
# , & # #

!
! #
" # #
, + 1, .0 %
2/(#%
20(# %
25(#
! getBill():
, #
# #
# + 1,
.0 %
2?(#%
2.(# %
27(# billType:
#

+ #
billType static #
#

Static Method Hiding


3 #
, = 3

= #throws # +
# #

static final %private final( 1, .0


3 # ! %29(#%
26(# %
/>(

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hhD3DA.htm 6/16/2006


Page 12 of 56

+ %
29( TubeLight# #
printBillType() %
.( ! + %
26( %/>( Light
printBillType() %
0( !

3 # # !
3 # ! super
! % /09(

Overriding vs. Overloading


4 % 50# 22.(
4 = % (
&
& #
# # #
# 3 #

3 + !
= ,% # !
super( !
+ ! #
! + 1, .0# getBill() %
/(
Light TubeLight %?( %
7( !
%
/2(# %
7( ,

Method Overloading Resolution

1, .5
testIfOn() %
2( %/(
OverloadResolution client.testIfOn(tubeLight) %
0(
%
2( %/(# tubeLight#
TubeLight# Light
#%/(# # false
client.testIfOn(light) %
5(
%2(# true

& #$ '

class Light { /* ... */ }

class TubeLight extends Light { /* ... */ }

public class OverloadResolution {


boolean testIfOn(Light aLight) { return true; } // (1)
boolean testIfOn(TubeLight aTubeLight) { return false; } // (2)
public static void main(String[] args) {

TubeLight tubeLight = new TubeLight();


Light light = new Light();

OverloadResolution client = new OverloadResolution();


System.out.println(client.testIfOn(tubeLight));// (3) ==> method at (2)

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hhD3DA.htm 6/16/2006


Page 13 of 56

System.out.println(client.testIfOn(light)); // (4) ==> method at (1)

}
}

& :

false
true

Object Reference super


this
! # this
% 50# 225( ! super % #
(# # !
% 52# 2//( ! super
+ super#
!
+ !
$ ! this ! # super !
< , #

+ 1, .?# demonstrate() %
6( NeonLight ! super
!
banner() ! %2>( %
5( Light
NeonLight getBill()
%
.( %
9( TubeLight ! # super %
2/( %
22(#

; NeonLight TubeLight# Light#


billType getBill %
2( %
/(# &
,super.super.getBill(20) NeonLight !
# & this
Light %
20( getBill()
%
.( TubeLight , # Light
% Light(# %
NeonLight( 4 #
getBill() TubeLight , !
getBill() Light NeonLight

3 %
25( ! super billType %
?( TubeLight 3 %
2?(
billType Light this #
<
# #
this @ # this !
#
getBill()

< # %
2.( %
27( super this #,

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hhD3DA.htm 6/16/2006


Page 14 of 56

() super * !

// Exceptions
class InvalidHoursException extends Exception {}
class NegativeHoursException extends InvalidHoursException {}
class ZeroHoursException extends InvalidHoursException {}

class Light {

protected String billType = "Small bill"; // (1)

protected double getBill(int noOfHours)


throws InvalidHoursException { // (2)
if (noOfHours < 0)
throw new NegativeHoursException();
double smallAmount = 10.0,
smallBill = smallAmount * noOfHours;
System.out.println(billType + ": " + smallBill);
return smallBill;
}

public static void printBillType() { // (3)


System.out.println("Small bill");
}

public void banner() { // (4)


System.out.println("Let there be light!");
}
}

class TubeLight extends Light {

public static String billType = "Large bill"; // (5) Hiding static field.

public double getBill(final int noOfHours)


throws ZeroHoursException { // (6) Overriding instance method.
if (noOfHours == 0)
throw new ZeroHoursException();
double largeAmount = 100.0,
largeBill = largeAmount * noOfHours;
System.out.println(billType + ": " + largeBill);
return largeBill;
}

public static void printBillType() { // (7) Hiding static method.


System.out.println(billType);
}

public double getBill() { // (8) Overloading method.


System.out.println("No bill");
return 0.0;
}
}

class NeonLight extends TubeLight {


// ...
public void demonstrate()
throws InvalidHoursException { // (9)

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hhD3DA.htm 6/16/2006


Page 15 of 56

super.banner(); // (10) Invokes method at (4)


super.getBill(); // (11) Invokes method at (8)
super.getBill(20); // (12) Invokes method at (6)
((Light) this).getBill(20); // (13) Invokes method at (6)
System.out.println(super.billType); // (14) Accesses field at (5)
System.out.println(((Light) this).billType); // (15) Accesses field at (1)
super.printBillType(); // (16) Invokes method at (7)
((Light) this).printBillType(); // (17) Invokes method at (3)
}
}

public class Client {


public static void main(String[] args)
throws InvalidHoursException {
NeonLight neonRef = new NeonLight();
neonRef.demonstrate();
}
}

& :

Let there be light!


No bill
Large bill: 2000.0
Large bill: 2000.0
Large bill
Small bill
Large bill
Small bill

Review Questions

" B

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hhD3DA.htm 6/16/2006


Page 16 of 56

& C # B

// Classes
class Foo {
private int i;
public void f() { /* ... */ }
public void g() { /* ... */ }
}

class Bar extends Foo {


public int j;
public void g() { /* ... */ }
}

// Declarations:
// ...
Foo a = new Foo();
Bar b = new Bar();
// ...

Bar Foo

b.f();

a.j = 5;

a.g();

b.i = 3;

( B

'

3 ,

C A#B# C# B , A# C , B#
void doIt() @ doIt() A
CB

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hhD3DA.htm 6/16/2006


Page 17 of 56

doIt();

super.doIt();

super.super.doIt();

this.super.doIt();

A.this.doIt();

+ ((A) this).doIt();

, B

// Filename: MyClass.java
public class MyClass {
public static void main(String[] args) {
C c = new C();
System.out.println(c.max(13, 29));
}
}

class A {
int max(int x, int y) { if (x>y) return x; else return y; }
}

class B extends A{
int max(int x, int y) { return super.max(y, x) - 10; }
}

class C extends B {
int max(int x, int y) { return super.max(x+10, y+10); }
}

max() B
super.max(y, x)

max()

13

23

29

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hhD3DA.htm 6/16/2006


Page 18 of 56

+ 39

- C #
print() B

// Filename: MyClass.java
public class MyClass extends MySuperclass {
public static void main(String[] args) {
MyClass object = new MyClass();
object.print();
}
public void print() {
// INSERT CODE HERE THAT WILL PRINT
// THE "Hello, world!" STRING FROM THE Message
// CLASS.
}
}

class MySuperclass {
Message msg = new Message();
}

class Message {
// The message that should be printed:
String text = "Hello, world!";
}

System.out.println(text);

System.out.println(Message.text);

System.out.println(msg.text);

System.out.println(object.msg.text);

System.out.println(super.msg.text);

+ System.out.println(object.super.msg.text);

6.3 Chaining Constructors Using this() and super()


; 55 227 & ! this super
./ /00

this() Constructor Call

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hhD3DA.htm 6/16/2006


Page 19 of 56

; #
#
+ 1, ..# Light
+ %0(# this
+ main() %5(#
! #

#$

class Light {

// Fields
private int noOfWatts; // wattage
private boolean indicator; // on or off
private String location; // placement
// Constructors
Light() { // (1) Explicit default constructor
noOfWatts = 0;
indicator = false;
location = "X";
System.out.println("Returning from default constructor no. 1.");
}
Light(int watts, boolean onOffState) { // (2) Non-default
noOfWatts = watts;
indicator = onOffState;
location = "X";
System.out.println("Returning from non-default constructor no. 2.");
}
Light(int noOfWatts, boolean indicator, String location) { // (3) Non-default
this.noOfWatts = noOfWatts;
this.indicator = indicator;
this.location = location;
System.out.println("Returning from non-default constructor no. 3.");
}
}

public class DemoConstructorCall {


public static void main(String[] args) { // (4)
System.out.println("Creating Light object no. 1.");
Light light1 = new Light();
System.out.println("Creating Light object no. 2.");
Light light2 = new Light(250, true);
System.out.println("Creating Light object no. 3.");
Light light3 = new Light(250, true, "attic");
}
}

& :

Creating Light object no. 1.


Returning from default constructor no. 1.
Creating Light object no. 2.
Returning from non-default constructor no. 2.
Creating Light object no. 3.
Returning from non-default constructor no. 3.

1, .7 this() #

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hhD3DA.htm 6/16/2006


Page 20 of 56

%
2(
%
/( 1, .. this() this()
# % ( #
%
2( %
/( this() !
+ main() %
5(# !
Light
; Light
,

+ #
# #
# !
" #
this(0, false)#
this(watt, ind, "X")# ,
# Light
,

- = this() this()
- *
,
,

, this()

class Light {
// Fields
private int noOfWatts;
private boolean indicator;
private String location;

// Constructors
Light() { // (1) Explicit default constructor
this(0, false);
System.out.println("Returning from default constructor no. 1.");
}
Light(int watt, boolean ind) { // (2) Non-default
this(watt, ind, "X");
System.out.println("Returning from non-default constructor no. 2.");
}
Light(int noOfWatts, boolean indicator, String location) { // (3) Non-default
this.noOfWatts = noOfWatts;
this.indicator = indicator;
this.location = location;
System.out.println("Returning from non-default constructor no. 3.");
}
}

public class DemoThisCall {


public static void main(String[] args) { // (4)
System.out.println("Creating Light object no. 1.");
Light light1 = new Light(); // (5)
System.out.println("Creating Light object no. 2.");
Light light2 = new Light(250, true); // (6)
System.out.println("Creating Light object no. 3.");
Light light3 = new Light(250, true, "attic"); // (7)

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hhD3DA.htm 6/16/2006


Page 21 of 56

}
}

& :

Creating Light object no. 1.


Returning from non-default constructor no. 3.
Returning from non-default constructor no. 2.
Returning from default constructor no. 1.
Creating Light object no. 2.
Returning from non-default constructor no. 3.
Returning from non-default constructor no. 2.
Creating Light object no. 3.
Returning from non-default constructor no. 3.

super() Constructor Call


super() !
8
3 super() ,
#
! # !

3 * % #
( ! super
& super !
@ # super() #
8

+ 1, .9# %
0( Light super() %
( %5( 3 # D
, D , %
.(
TubeLight super() % ( %
7( super()
%0( Light

- super()

class Light {
// Fields
private int noOfWatts;
private boolean indicator;
private String location;

// Constructors
Light() { // (1) Explicit default constructor
this(0, false);
System.out.println(
"Returning from default constructor no. 1 in class Light");
}
Light(int watt, boolean ind) { // (2) Non-default
this(watt, ind, "X");
System.out.println(
"Returning from non-default constructor no. 2 in class Light");
}

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hhD3DA.htm 6/16/2006


Page 22 of 56

Light(int noOfWatts, boolean indicator, String location) { // (3) Non-default


super(); // (4)
this.noOfWatts = noOfWatts;
this.indicator = indicator;
this.location = location;
System.out.println(
"Returning from non-default constructor no. 3 in class Light");
}
}
class TubeLight extends Light {
// Instance variables
private int tubeLength;
private int colorNo;

TubeLight(int tubeLength, int colorNo) { // (5) Non-default


this(tubeLength, colorNo, 100, true, "Unknown");
System.out.println(
"Returning from non-default constructor no. 1 in class TubeLight");
}

TubeLight(int tubeLength, int colorNo, int noOfWatts,


boolean indicator, String location) { // (6) Non-default
super(noOfWatts, indicator, location); // (7)
this.tubeLength = tubeLength;
this.colorNo = colorNo;
System.out.println(
"Returning from non-default constructor no. 2 in class TubeLight");
}
}
public class Chaining {
public static void main(String[] args) {
System.out.println("Creating a TubeLight object.");
TubeLight tubeLightRef = new TubeLight(20, 5); // (8)
}
}

& :

Creating a TubeLight object.


Returning from non-default constructor no. 3 in class Light
Returning from non-default constructor no. 2 in class TubeLight
Returning from non-default constructor no. 1 in class TubeLight

super() this() : # super()


#
this() super()
this() #
! super() - this()
# super()

# #
# Object A
, # super()
Object
#
% E (
1, .9 TubeLight

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hhD3DA.htm 6/16/2006


Page 23 of 56

+ this() % this()
! ( , super()# super() % (
! + #
this() super() # super()

class A {
public A() {}
// ...
}
class B extends A {
// no constructors
// ...
}

class A {
public A() { super(); } // (1)
// ...
}
class B extends A {
public B() { super(); } // (2)
// ...
}

+ % # (#
super()
, # super()

class NeonLight extends TubeLight {


// Field
String sign;

NeonLight() { // (1)
super(10, 2, 100, true, "Roof-top"); // (2) Cannot be commented out.
sign = "All will be revealed!";
}
// ...
}

NeonLight %
2( %
/(
TubeLight + #
super() % (
TubeLight# TubeLight
NeonLight , super()
% ( %
/(

+ % # (#
3

, 3 ,

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hhD3DA.htm 6/16/2006


Page 24 of 56

super() # # !
super()

Review Questions

. C # MySubclass
B

class MySuper {
int number;
MySuper(int i) { number = i; }
}

class MySub extends MySuper {


int count;
MySub(int cnt, int num) {
super(num);
count=cnt;
}

// INSERT ADDITIONAL CONSTRUCTOR HERE


}

MySub() {}

MySub(int cnt) { count = cnt; }

MySub(int cnt) { super(); count = cnt; }

MySub(int cnt) { count = cnt; super(cnt); }

MySub(int cnt) { this(cnt, cnt); }

+ MySub(int cnt) { super(cnt); this(cnt, 0); }

/ B

3 super() this() ,

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hhD3DA.htm 6/16/2006


Page 25 of 56

+ #
super()

+ super() this()
# this()

+ super() # this()

; super()
!#

// Filename: MyClass.java
public class MyClass {
public static void main(String[] args) {
B b = new B("Test");
}
}

class A {
A() { this("1", "2"); }

A(String s, String t) { this(s + t); }

A(String s) { System.out.println(s); }
}

class B extends A {
B(String s) { System.out.println(s); }

B(String s, String t) { this(t + s + "3"); }

B() { super("4"); };
}

+ Test

+ Test Test

+ 123 Test

+ 12 Test

+ 4 Test

6.4 Interfaces

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hhD3DA.htm 6/16/2006


Page 26 of 56

1, 3

# #
# + - #
#

Defining Interfaces
3 ,:

# $ interface # $
# $ // Interface header

{ // Interface body
# $
# $
# $
# $
}

+ # ! interface +
# :

% 57# 202(

% .5# /?5(

% .5# /??(

% .5# /?5(

% 72# /95(

3 # #abstract
#
) abstract

# public
public

+
- 3'+ ,
! : java.lang.Cloneable#java.io.Serializable#
java.util.EventListener

Method Prototype Declarations

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hhD3DA.htm 6/16/2006


Page 27 of 56

3 #
abstract public 3
, abstract % 52># 257(
@ # abstract public #

F GF G (F G) F G;

1, .6 :IStack %
2( ISafeStack %
?(
=

. +

interface IStack { // (1)


void push(Object item);
Object pop();
}

class StackImpl implements IStack { // (2)


protected Object[] stackArray;
protected int tos; // top of stack

public StackImpl(int capacity) {


stackArray = new Object[capacity];
tos = -1;
}

public void push(Object item) // (3)


{ stackArray[++tos] = item; }

public Object pop() { // (4)


Object objRef = stackArray[tos];
stackArray[tos] = null;
tos--;
return objRef;
}

public Object peek() { return stackArray[tos]; }


}

interface ISafeStack extends IStack { // (5)


boolean isEmpty();
boolean isFull();
}

class SafeStackImpl extends StackImpl implements ISafeStack { // (6)

public SafeStackImpl(int capacity) { super(capacity); }


public boolean isEmpty() { return tos < 0; } // (7)
public boolean isFull() { return tos >= stackArray.length-1; }// (8)
}
public class StackUser {

public static void main(String[] args) { // (9)


SafeStackImpl safeStackRef = new SafeStackImpl(10);
StackImpl stackRef = safeStackRef;
ISafeStack isafeStackRef = safeStackRef;
IStack istackRef = safeStackRef;

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hhD3DA.htm 6/16/2006


Page 28 of 56

Object objRef = safeStackRef;

safeStackRef.push("Dollars"); // (10)
stackRef.push("Kroner");
System.out.println(isafeStackRef.pop());
System.out.println(istackRef.pop());
System.out.println(objRef.getClass());
}
}

& :

Kroner
Dollars
class SafeStackImpl

Implementing Interfaces
3 # #8 3
= implements
public
% ( 3
, * throws #
* #

3 #
, implements

+ 1, .6# StackImpl IStack


implements %/(
%
0( %
5( ; public
#

3 #% #
( abstract % 59#
205( A static#
" +

, % (
; # ;

@ #
#

Extending Interfaces
3 , # extends $ ! , #
, , %
(# ; #
#

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hhD3DA.htm 6/16/2006


Page 29 of 56

3 #
public 3
& 4
#

1, .6 , - + 1, .6#
ISafeStack , IStack %?( SafeStackImpl ,
StackImpl ISafeStack %
.(
1, .6
< .0

"

+ $4 # &
% & < .0 +
# ! #
- Object Object
< .0 ,

+ SafeStackImpl ISafeStack :
push() pop() StackImpl#
isFull() isEmpty() ISafeStack
ISafeStack IStack 3
SafeStackImpl SafeStackImpl
IStack : ISafeStack

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hhD3DA.htm 6/16/2006


Page 30 of 56

IStack
< .0 SafeStackImpl

A !
:

: ,
% E (

4 : ,
% E (

" 4 :

3 #
H * + 1,
.6# SafeStackImpl main() StackUser
%
6( * #
'
.7

Constants in Interfaces
3
public#static final
8 8 , % 9/#
002(

3 % ( =
# , @ #
, #
=
1, .2>#
= %
2( %
/(#

1, ,
+ # +
# =

/0 +

interface Constants {
double PI_APPROXIMATION = 3.14;
String AREA_UNITS = " sq.cm.";
String LENGTH_UNITS = " cm.";
}

public class Client implements Constants {


public static void main(String[] args) {
double radius = 1.5;
System.out.println("Area of circle is " +
(PI_APPROXIMATION*radius*radius) +

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hhD3DA.htm 6/16/2006


Page 31 of 56

AREA_UNITS); // (1) Direct access.


System.out.println("Circumference of circle is " +
(2*Constants.PI_APPROXIMATION*radius) +
Constants.LENGTH_UNITS); // (2) Fully qualified name.
}
}

& :

Area of circle is 7.0649999999999995 sq.cm.


Circumference of circle is 9.42 cm.

Review Questions

+ ,

+ ,

4 static

" B

public static int answer = 42;

int answer;

final static int answer = 42;

public int answer = 42;

private final static int answer = 42;

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hhD3DA.htm 6/16/2006


Page 32 of 56

& B

! extends

! extends

! implements

! implements

! implements

( B

// Filename: MyClass.java
abstract class MyClass implements Interface1, Interface2 {
public void f() { }
public void g() { }
}

interface Interface1 {
int VAL_A = 1;
int VAL_B = 2;

void f();
void g();
}

interface Interface2 {
int VAL_B = 3;
int VAL_C = 4;

void g();
void h();
}

Interface1 Interface2 # #MyClass

MyClass Interface1 + void h()


Interface2

void g() # #

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hhD3DA.htm 6/16/2006


Page 33 of 56

int VAL_B # #

A #

C #
B

interface MyConstants {
int r = 42;
int s = 69;
// INSERT CODE HERE
}

final double circumference = 2*Math.PI*r;

int total = total + r + s;

int AREA = r*s;

public static MAIN = 15;

protected int CODE = 31337;

6.5 Completing the Type Hierarchy


.2 8 - &
&

1 1 0
1 0

' '
; # # % ( H

3 - 3 %
boolean[]#Object[]#StackImpl[](
< .0
< .5 3
I I []
SafeStackImpl StackImpl #
SafeStackImpl[] StackImpl[]# # #
< .5

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hhD3DA.htm 6/16/2006


Page 34 of 56

& + 1

< < .5# 8 :

' Object # #
#

3 Object[]#
A Object[] Object

+ #

# %
abstract ( + # iSafeStackArray
ISafeStack[]#% # ISafeStack( ,
ISafeStack
ISafeStack 8
:

ISafeStack[] iSafeStackArray = new ISafeStack[5];

3 , ! #
% .7# /7/( @ # !
# ,

# %
StackImpl[](
%
SafeStackImpl[](:

StackImpl[] stackImplArray = new SafeStackImpl[2]; // (1)

StackImpl SafeStackImpl# :

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hhD3DA.htm 6/16/2006


Page 35 of 56

stackImplArray[0] = new SafeStackImpl(10); // (2)

%
/( SafeStackImpl SafeStackImpl[] % #
SafeStackImpl( %
2(

stackImplArray[i]#%
0 i < 2(# StackImpl#
:

stackImplArray[1] = new StackImpl(20); // (3) ArrayStoreException

3 #
stackImplArray SafeStackImpl[] @ #
%0( ArrayStoreException # SafeStackImpl
[] StackImpl

6.6 Assigning, Passing, and Casting Reference Values


H #! # # # <
#

#
= ,
% (#
= , % ( + #
# = ,

Reference Value Assignment Conversions


H #

2 + 0

interface IStack { /* From Example 6.9 */ }


interface ISafeStack extends IStack { /* From Example 6.9 */ }
class StackImpl implements IStack { /* From Example 6.9 */ }
class SafeStackImpl extends StackImpl
implements ISafeStack { /* From Example 6.9 */ }

public class ReferenceConversion {

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hhD3DA.htm 6/16/2006


Page 36 of 56

public static void main(String[] args) {


// Reference declarations
Object objRef;
StackImpl stackRef;
SafeStackImpl safeStackRef;
IStack iStackRef;
ISafeStack iSafeStackRef;

// SourceType is a class type


safeStackRef = new SafeStackImpl(10);
objRef = safeStackRef;// (1) Always possible
stackRef = safeStackRef;// (2) Subclass to superclass assignment
iStackRef = stackRef; // (3) StackImpl implements IStack
iSafeStackRef = safeStackRef;// (4) SafeStackImpl implements ISafeStack

// SourceType is an interface type


objRef = iStackRef; // (5) Always possible
iStackRef = iSafeStackRef; // (6) Sub- to super-interface assignment

// SourceType is an array type.


Object[] objArray = new Object[3];
StackImpl[] stackArray = new StackImpl[3];
SafeStackImpl[] safeStackArray = new SafeStackImpl[5];
ISafeStack[] iSafeStackArray = new ISafeStack[5];
int[] intArray = new int[10];

// Reference value assignments


objRef = objArray; // (7) Always possible
objRef = stackArray; // (8) Always possible
objArray = stackArray; // (9) Always possible
objArray = iSafeStackArray;// (10) Always possible
objRef = intArray; // (11) Always possible
// objArray = intArray; // (12) Compile-time error
stackArray = safeStackArray; // (13) Subclass array to superclass array
iSafeStackArray =
safeStackArray; // (14) SafeStackImpl implements ISafeStack

// Parameter Conversion
System.out.println("First call:");
sendParams(stackRef, safeStackRef, iStackRef,
safeStackArray, iSafeStackArray); // (15)
// Call Signature: sendParams(StackImpl, SafeStackImpl, IStack,
// SafeStackImpl[], ISafeStack[]);

System.out.println("Second call:");
sendParams(iSafeStackArray, stackRef, iSafeStackRef,
stackArray, safeStackArray); // (16)
// Call Signature: sendParams(ISafeStack[], StackImpl, ISafeStack,
// StackImpl[], SafeStackImpl[]);
}

public static void sendParams(Object objRefParam, StackImpl stackRefParam,


IStack iStackRefParam, StackImpl[] stackArrayParam,
final IStack[] iStackArrayParam) { // (17)
// Signature: sendParams(Object, StackImpl, IStack, StackImpl[], IStack[])
// Print class name of object denoted by the reference at runtime.
System.out.println(objRefParam.getClass());
System.out.println(stackRefParam.getClass());
System.out.println(iStackRefParam.getClass());
System.out.println(stackArrayParam.getClass());

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hhD3DA.htm 6/16/2006


Page 37 of 56

System.out.println(iStackArrayParam.getClass());
}
}

& :

First call:
class SafeStackImpl
class SafeStackImpl
class SafeStackImpl
class [LSafeStackImpl;
class [LSafeStackImpl;
Second call:
class [LSafeStackImpl;
class SafeStackImpl
class SafeStackImpl
class [LSafeStackImpl;
class [LSafeStackImpl;

# :

SourceType srcRef;
// srcRef is appropriately initialized.
DestinationType destRef = srcRef;

+ # srcRef %
( DestinationType
1, .22

+ SourceType # srcRef
destRef # DestinationType :

DestinationType SourceType

DestinationType SourceType

objRef = safeStackRef; // (1) Always possible


stackRef = safeStackRef; // (2) Subclass to superclass assignment
iStackRef = stackRef; // (3) StackImpl implements IStack
iSafeStackRef = safeStackRef; // (4) SafeStackImpl implements ISafeStack

+ SourceType # srcRef
destRef # DestinationType :

DestinationType Object

DestinationType SourceType

objRef = iStackRef; // (5) Always possible


iStackRef = iSafeStackRef; // (6) Subinterface to superinterface assignment

+ SourceType # srcRef
destRef # DestinationType :

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hhD3DA.htm 6/16/2006


Page 38 of 56

DestinationType Object

DestinationType # SourceType
DestinationType

objRef = objArray; // (7) Always possible


objRef = stackArray; // (8) Always possible
objArray = stackArray; // (9) Always possible
objArray = iSafeStackArray;// (10) Always possible
objRef = intArray; // (11) Always possible
// objArray = intArray; // (12) Compile-time error
stackArray = safeStackArray; // (13) Subclass array to superclass array
iSafeStackArray =
safeStackArray; // (14) SafeStackImpl implements ISafeStack

% !
( % !
(

Parameter Passing Conversions

# - % 026# 96(# =

+ 1, .22# sendParams() %
27( #
:

sendParams(Object, StackImpl, IStack, StackImpl[], IStack[])

%
2?( # :

sendParams(StackImpl, SafeStackImpl, IStack, SafeStackImpl[], ISafeStack[]);

A
# %
2.(
, + :

sendParams(ISafeStack[], StackImpl, ISafeStack, StackImpl[], SafeStackImpl[]);

3 #
1, .22
#
SafeStackImpl SafeStackImpl[] [L
% Class.getName() 3'+
(

java.util ! ! Object
# %
; 22(

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hhD3DA.htm 6/16/2006


Page 39 of 56

Reference Casting and instanceof Operator

, # $ # $ # $
,:

(# $) # $

3 , ! # $
# $# # # $
# $ + # ClassCastException null

instanceof ,% !
(:

# $ instanceof # $

instanceof true %
# $(
%
# $(# false null
+ instanceof true# ,
instanceof = !
! ,

! # $
# $
# $ # $ + #
# instanceof
3 # # $

# $ #
$ Light String# #
# $ # $
Light String instanceof #
%/( %0( 1, .2/ # $ # $
Light TubeLight# # Light TubeLight
TubeLight % ( < .0 #
! instanceof Light TubeLight
%5( %?(# # 1, .2/

3 # instanceof %
5( false
light1 Light LightBulb,
TubeLight 3 %
?(
ClassCastException
# ClassCastException A
instanceof false#
ClassCastException

+ 1, .2/# instanceof %
.( false#
light1 LightBulb#
SpotLightBulb %
7(

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hhD3DA.htm 6/16/2006


Page 40 of 56

ClassCastException

%
9(#%
6(# %
2>( instanceof

light1 Light 8
NeonLight %
9( instanceof %
6( true#
light1 NeonLight#
TubeLight ! # %
2>( +
instanceof true#

instanceof #

class Light { /* ... */ }


class LightBulb extends Light { /* ... */ }
class SpotLightBulb extends LightBulb { /* ... */ }
class TubeLight extends Light { /* ... */ }
class NeonLight extends TubeLight { /* ... */ }

public class WhoAmI {


public static void main(String[] args) {
boolean result1, result2, result3, result4, result5;
Light light1 = new LightBulb(); // (1)
// String str = (String) light1; // (2) Compile-time error.
// result1 = light1 instanceof String; // (3) Compile-time error.
result2 = light1 instanceof TubeLight; // (4) false. Peer class.
// TubeLight tubeLight1 = (TubeLight) light1; // (5) ClassCastException.

result3 = light1 instanceof SpotLightBulb; // (6) false: Superclass


// SpotLightBulb spotRef = (SpotLightBulb) light1;// (7) ClassCastException

light1 = new NeonLight(); // (8)


if (light1 instanceof TubeLight) { // (9) true
TubeLight tubeLight2 = (TubeLight) light1; // (10) OK
// Can now use tubeLight2 to access object of class NeonLight.
}
}
}

3 # instanceof

A
3 #
+ #
#

1, .20 , instanceof +
null
# %
2(#%
/(# %2.( 3
# %
5( 3
# %
2>( 3
#
%
.( 3 Object Object[] #
%
25( %
2?(#

") instanceof #

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hhD3DA.htm 6/16/2006


Page 41 of 56

interface IStack { /* From Example 6.9 */ }


interface ISafeStack extends IStack { /* From Example 6.9 */ }
class StackImpl implements IStack { /* From Example 6.9 */ }
class SafeStackImpl extends StackImpl
implements ISafeStack { /* From Example 6.9 */ }

public class Identification {


public static void main(String[] args) {
Object obj = new Object();
StackImpl stack = new StackImpl(10);
SafeStackImpl safeStack = new SafeStackImpl(5);
IStack iStack;
System.out.println("(1): " +
(null instanceof Object)); // Always false.
System.out.println("(2): " +
(null instanceof IStack)); // Always false.

System.out.println("(3): " + // true: instance of subclass of


(stack instanceof Object)); // Object.
System.out.println("(4): " +
(obj instanceof StackImpl)); // false: Downcasting.
System.out.println("(5): " +
(stack instanceof StackImpl)); // true: instance of StackImpl.

System.out.println("(6): " + // false: Object does not implement


(obj instanceof IStack)); // IStack.
System.out.println("(7): " + // true: SafeStackImpl implements
(safeStack instanceof IStack)); // IStack.

obj = stack; // Assigning subclass to superclass.


System.out.println("(8): " +
(obj instanceof StackImpl)); // true: instance of StackImpl.
System.out.println("(9): " + // true: StackImpl implements
(obj instanceof IStack)); // IStack.
System.out.println("(10): " +
(obj instanceof String)); // false: No relationship.

iStack = (IStack) obj; // Cast required: superclass assigned subclass.


System.out.println("(11): " + // true: instance of subclass
(iStack instanceof Object)); // of Object.
System.out.println("(12): " +
(iStack instanceof StackImpl)); // true: instance of StackImpl.

String[] strArray = new String[10];


// System.out.println("(13): " + // Compile-time error,
// (strArray instanceof String); // no relationship.
System.out.println("(14): " +
(strArray instanceof Object)); // true: array subclass of Object.
System.out.println("(15): " +
(strArray instanceof Object[])); // true: array subclass of Object[].
System.out.println("(16): " +
(strArray[0] instanceof Object));// false: strArray[0] is null.
strArray[0] = "Amoeba strip";
System.out.println("(17): " +
(strArray[0] instanceof String));// true: instance of String.
}
}

& :

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hhD3DA.htm 6/16/2006


Page 42 of 56

(1): false
(2): false
(3): true
(4): false
(5): true
(6): false
(7): true
(8): true
(9): true
(10): false
(11): true
(12): true
(14): true
(15): true
(16): false
(17): true

Converting References of Class and Interface Types


H
, A
# = ,
, :

IStack istackOne = new StackImpl(5); // Upcasting


StackImpl stackTwo = (StackImpl) istackOne; // Downcasting

$ istackOne IStack# IStack


! StackImpl @ #
StackImpl
StackImpl :

Object obj1 = istackOne.pop(); // OK. Method in IStack interface.


Object obj2 = istackOne.peek(); // Not OK. Method not in IStack interface.
Object obj3 = ((StackImpl) istackOne).peek(); // OK. Method in StackImpl class.

Review Questions

, C # B

// Filename: MyClass.java
public class MyClass {
public static void main(String[] args) {
A[] arrA;
B[] arrB;

arrA = new A[10];

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hhD3DA.htm 6/16/2006


Page 43 of 56

arrB = new B[20];


arrA = arrB; // (1)
arrB = (B[]) arrA; // (2)
arrA = new A[10];
arrB = (B[]) arrA; // (3)
}
}

class A {}

class B extends A {}

%
2(

java.lang.ClassCastException
%
/(

java.lang.ClassCastException
%
0(

# (B[])
%
/( %
0(

# (B[])
%
/( %
0(

- B

// Filename: MyClass.java
class MyClass {
public static void main(String[] args) {
MyClass a;
MySubclass b;

a = new MyClass(); // (1)


b = new MySubclass(); // (2)

a = b; // (3)
b = a; // (4)

a = new MySubclass(); // (5)


b = new MyClass(); // (6)
}
}

class MySubclass extends MyClass {}

%
2(

%
/(

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hhD3DA.htm 6/16/2006


Page 44 of 56

%
0(

%
5(

%
?(

+ %
.(

. C #
B

// Definitions:
interface I1 {}
interface I2 {}
class C1 implements I1 {}
class C2 implements I2 {}
class C3 extends C1 implements I2 {}
// Reference declarations:
// ...
C1 obj1;
C2 obj2;
C3 obj3;
// ...

obj2 = obj1;

obj3 = obj1;

obj3 = obj2;

I1 a = obj2;

I1 b = obj3;

+ I2 c = obj1;

/ C #
y = (Sub) xB

// Class definitions:
class Super {}
class Sub extends Super {}

// Reference declarations
// ...
Super x;
Sub y;
// ...

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hhD3DA.htm 6/16/2006


Page 45 of 56

) # (Sub)

) # (Sub)

C #
B

// Definitions:
interface A {}
class B {}
class C extends B implements A {}
class D implements A {}

// Declaration statements:
// [...]
B b = new B();
C c = new C();
D d = new D();
// [...]

c = d;

d = c;

A a = d;

d = (D) c;

c = b;

// Filename: MyClass.java
public class MyClass {
public static void main(String[] args) {
B b = new C();
A a = b;
if (a instanceof A) System.out.println("A");
if (a instanceof B) System.out.println("B");
if (a instanceof C) System.out.println("C");
if (a instanceof D) System.out.println("D");
}
}

class A {}
class B extends A {}

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hhD3DA.htm 6/16/2006


Page 46 of 56

class C extends B {}
class D extends C {}

" C A#B# C# B A C B#
, true o
B A CB

(o instanceof B) && (!(o instanceof A))

(o instanceof B) && (!(o instanceof C))

!((o instanceof A) || (o instanceof B))

(o instanceof B)

(o instanceof B) && !((o instanceof A) || (o instanceof C))

& # I#J#C, D +
B

public class MyClass {


public static void main(String[] args) {
I x = new D();
if (x instanceof I) System.out.println("I");
if (x instanceof J) System.out.println("J");
if (x instanceof C) System.out.println("C");
if (x instanceof D) System.out.println("D");
}
}

interface I{}
interface J{}
class C implements I {}
class D extends C implements J {}

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hhD3DA.htm 6/16/2006


Page 47 of 56

<

6.7 Polymorphism and Dynamic Method Lookup


#
'
, 3 , #

private ! #
,
) !
# @ # private
#
private

< .? 1, .25
draw() Shape
draw() %
0( %5( 1, .25#
! shapes Shape
Circle# Rectangle Square# %
2( 3 #
! draw() , #
drawables %
/(#
IDrawable
IDrawable !
Shape shapes + draw() #
,
drawables# IDrawable

( 2 '

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hhD3DA.htm 6/16/2006


Page 48 of 56

' !
# #

&2 3 ' 4 5

interface IDrawable {
void draw();
}

class Shape implements IDrawable {


public void draw() { System.out.println("Drawing a Shape."); }
}

class Circle extends Shape {


public void draw() { System.out.println("Drawing a Circle."); }
}

class Rectangle extends Shape {


public void draw() { System.out.println("Drawing a Rectangle."); }
}

class Square extends Rectangle {


public void draw() { System.out.println("Drawing a Square."); }
}

class Map implements IDrawable {


public void draw() { System.out.println("Drawing a Map."); }
}

public class PolymorphRefs {

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hhD3DA.htm 6/16/2006


Page 49 of 56

public static void main(String[] args) {


Shape[] shapes = {new Circle(), new Rectangle(), new Square()}; // (1)
IDrawable[] drawables = {new Shape(), new Rectangle(), new Map()};// (2)

System.out.println("Draw shapes:");
for (int i = 0; i < shapes.length; i++) // (3)
shapes[i].draw();

System.out.println("Draw drawables:");
for (int i = 0; i < drawables.length; i++) // (4)
drawables[i].draw();
}
}

& :

Draw shapes:
Drawing a Circle.
Drawing a Rectangle.
Drawing a Square.
Draw drawables:
Drawing a Shape.
Drawing a Rectangle.
Drawing a Map.

Review Questions

( B

public class Polymorphism {


public static void main(String[] args) {
A ref1 = new C();
B ref2 = (B) ref1;
System.out.println(ref2.f());
}
}

class A { int f() { return 0; } }


class B extends A { int f() { return 1; } }
class C extends B { int f() { return 2; } }

# ClassCastException

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hhD3DA.htm 6/16/2006


Page 50 of 56

public class Polymorphism2 {


public static void main(String[] args) {
A ref1 = new C();
B ref2 = (B) ref1;
System.out.println(ref2.g());
}
}

class A {
private int f() { return 0; }
public int g() { return 3; }
}
class B extends A {
private int f() { return 1; }
public int g() { return f(); }
}
class C extends B {
public int f() { return 2; }
}

6.8 Inheritance vs. Aggregation


Encapsulation
3

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hhD3DA.htm 6/16/2006


Page 51 of 56

&

1 ! *
=
1 , #
#

Choosing between Inheritance and Aggregation


< .. $4 #
= # !
! 3 !
1, .2? ,
# =
! Node %
2( # :
, LinkedList %
/( ! !
A !#

( 3 6

class Node { // (1)


private Object data; // Data
private Node next; // Next node

// Constructor for initializing data and reference to the next node.


Node(Object data, Node next) {
this.data = data;
this.next = next;
}

// Methods
public void setData(Object obj) { data = obj; }
public Object getData() { return data; }
public void setNext(Node node) { next = node; }
public Node getNext() { return next; }
}

class LinkedList { // (2)


protected Node head = null;
protected Node tail = null;

// Methods
public boolean isEmpty() { return head == null; }
public void insertInFront(Object dataObj) {
if (isEmpty()) head = tail = new Node(dataObj, null);
else head = new Node(dataObj, head);
}
public void insertAtBack(Object dataObj) {
if (isEmpty())
head = tail = new Node(dataObj, null);
else {
tail.setNext(new Node(dataObj, null));
tail = tail.getNext();
}
}

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hhD3DA.htm 6/16/2006


Page 52 of 56

public Object deleteFromFront() {


if (isEmpty()) return null;
Node removed = head;
if (head == tail) head = tail = null;
else head = head.getNext();
return removed.getData();
}
}

class QueueByAggregation { // (3)


private LinkedList qList;

// Constructor
QueueByAggregation() {
qList = new LinkedList();
}

// Methods
public boolean isEmpty() { return qList.isEmpty(); }
public void enqueue(Object item) { qList.insertAtBack(item); }
public Object dequeue() {
if (qList.isEmpty()) return null;
else return qList.deleteFromFront();
}
public Object peek() {
return (qList.isEmpty() ? null : qList.head.getData());
}
}

class StackByInheritance extends LinkedList { // (4)


public void push(Object item) { insertInFront(item); }
public Object pop() {
if (isEmpty()) return null;
else return deleteFromFront();
}
public Object peek() {
return (isEmpty() ? null : head.getData());
}
}

public class Client { // (5)


public static void main(String[] args) {
String string1 = "Queues are boring to stand in!";
int length1 = string1.length();
QueueByAggregation queue = new QueueByAggregation();
for (int i = 0; i<length1; i++)
queue.enqueue(new Character(string1.charAt(i)));
while (!queue.isEmpty())
System.out.print((Character) queue.dequeue());
System.out.println();

String string2 = "!no tis ot nuf era skcatS";


int length2 = string2.length();
StackByInheritance stack = new StackByInheritance();
for (int i = 0; i<length2; i++)
stack.push(new Character(string2.charAt(i)));
stack.insertAtBack(new Character('!')); // (6)
while (!stack.isEmpty())
System.out.print((Character) stack.pop());
System.out.println();

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hhD3DA.htm 6/16/2006


Page 53 of 56

}
}

& :

Queues are boring to stand in!


Stacks are fun to sit on!!

3 6

;
3
= " #
3 < , #
Employee#
% ( ;

; 1
#
1, .2? % .( StackByInheritance %
5(
LinkedList %/(# !
3 #
! # % .( $ #
QueueByAggregation %0( =
= LinkedList ; =
# # !

#
8 ;
= % (

' ;
!
+ #

Review Questions

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hhD3DA.htm 6/16/2006


Page 54 of 56

, C # B

public interface HeavenlyBody { String describe(); }

class Star {
String starName;
public String describe() { return "star " + starName; }
}

class Planet extends Star {


String name;
public String describe() {
return "planet " + name + " orbiting star " + starName;
}
}

# Planet Star

starName
bodyName Star

starName
name Star

3 Planet HeavenlyBody

- C # B

public interface HeavenlyBody { String describe(); }

class Star implements HeavenlyBody {


String starName;
public String describe() { return "star " + starName; }
}

class Planet {
String name;
Star orbiting;
public String describe() {
return "planet " + name + " orbiting " + orbiting.describe();
}
}

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hhD3DA.htm 6/16/2006


Page 55 of 56

# Planet Star

starName
bodyName Star

starName
name Star

3 Planet HeavenlyBody

Chapter Summary

&&'

super

this() super() #

# #

instanceof

% ( % (

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hhD3DA.htm 6/16/2006


Page 56 of 56

Programming Exercises

) Function evaluate !
int int G

; Half Function 4 !
evaluate() int /

+ # ! int
#

Half

H , :
! Function
Half

; Print Function#
int #

A # int 2 2>
:

' Print

@ # Half
Print

file://C:\Documents and Settings\cdot\Local Settings\Temp\~hhD3DA.htm 6/16/2006

Você também pode gostar