You are on page 1of 30

Page 1 of 30

Chapter 8. Object Lifetime


Exam Objectives

! " #

Supplementary Objectives

"

$ # " "
% # " "

" #
new

8.1 Garbage Collection


&
" '
( %
# )
%
#
new
# #
# %

*
+ % )
, -./0 * # %
#
1

Reachable References

2 # 3

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


Page 2 of 30

2 #
2
, -./0

+ # #
%# )
45 ) 1
% )
45% #
, 6 70 2 2
& # %
88 9:9
#
; % # #
< % % # +
% %

2 # " = :9 + # #
,9 .
0 #
# #
# %#

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


Page 3 of 30

2
2 %
! %
2
2

2 + # >
2

# % 2
&
%
*# %

= = :9 # o4%o5%o11%o12%o14% o15

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


Page 4 of 30

< o13 o16 % %

= # %
%
2 o1%o2% o3 %
% < % o5%o6% o7
% % %05% <
o8%o10%o11% o9 , 0
%
< o9 o11 % o11 <
o8 o10

#
? % #
# #
%# " , -.@0
) %
"

+ %
? ,
0 2
# # % #
# # # #
# ;

java.lang.ref.Reference ,
SoftReference%
WeakReference%PhantomReference0
, 02
%
#

%#

Facilitating Garbage Collection


# % %
+# #
2 %
" #
2

6 % %
# + % finally
try-catch-finally , 8/% 9::0
% # # % #

" %

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


Page 5 of 30

<
# %
%
% # *# %
# +
% %

import java.io.*;

class WellbehavedClass {
// ...
void wellbehavedMethod() {

File aFile;
long[] bigArray = new long[20000];

// ... uses local variables ...

// Does cleanup (before starting something extensive)


aFile = null; // (1)
bigArray = null; // (2)

// Start some other extensive activity


// ...
}
// ...
}

+ % null ,
90 ,
.0%

# %
" A #

+ # %

!
%

& :9 # 6
HeavyItem # % # # #
& HeavyItem
finalize() Object +
$# "
# , " % -.@0
# HeavyItem
% HeavyItem

+ & :9% RecyclingBin createHeavyItem() ,


@0 +
% HeavyItem ,
80
itemA ,B0% # HeavyItem ,
B0
+

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


Page 6 of 30

+ & :9% RecyclingBin createList() ,


/0 +
item1%# HeavyItem
% HeavyItem
2 %
+ %
, 0

class HeavyItem { // (1)


int[] itemBody;
String itemID;
HeavyItem nextItem;

HeavyItem(String ID, HeavyItem itemRef) { // (2)


itemBody = new int[100000];
itemID = ID;
nextItem = itemRef;
}
protected void finalize() throws Throwable { // (3)
System.out.println(itemID + ": recycled.");
super.finalize();
}
}

public class RecyclingBin {

public static HeavyItem createHeavyItem(String itemID) { // (4)


HeavyItem itemA = new HeavyItem(itemID + " local item", null); // (5)
itemA = new HeavyItem(itemID, null); // (6)
System.out.println("Return from creating HeavyItem " + itemID);
return itemA; // (7)
}

public static HeavyItem createList(String listID) { // (8)


HeavyItem item3 = new HeavyItem(listID + ": item3", null); // (9)
HeavyItem item2 = new HeavyItem(listID + ": item2", item3); // (10)
HeavyItem item1 = new HeavyItem(listID + ": item1", item2); // (11)
System.out.println("Return from creating list " + listID);
return item1; // (12)
}

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


HeavyItem list = createList("X"); // (14)
list = createList("Y"); // (15)

HeavyItem itemOne = createHeavyItem("One"); // (16)


HeavyItem itemTwo = createHeavyItem("Two"); // (17)
itemOne = null; // (18)
createHeavyItem("Three"); // (19)
createHeavyItem("Four"); // (20)
System.out.println("Return from main().");
}
}

C 3

Return from creating list X

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


Page 7 of 30

Return from creating list Y


X: item3: recycled.
X: item2: recycled.
X: item1: recycled.
Return from creating HeavyItem One
Return from creating HeavyItem Two
Return from creating HeavyItem Three
Three local item: recycled.
Three: recycled.
Two local item: recycled.
Return from creating HeavyItem Four
One local item: recycled.
One: recycled.
Return from main().

+ & :9% main() ,9-0 RecyclingBin


createHeavyItem() createList() + X ,9@0%
,980% X ,
980
Y list% 1
main()

main() # ,
9B0 ,9/0%
itemOne itemTwo% itemOne ,
9:0% HeavyItem
# One # createHeavyItem()
,970 ,.D0 HeavyItem %# %

< Y,
list0 HeavyItem # Two , itemTwo0
1 # main() 2 #
HeavyItem # Four Five # %
,
970 ,
.D0
% 2

Object Finalization

< "
finalize()
finalize()
Object

protected void finalize() throws Throwable

2 finalize() 2
" Object

2 " % % # , 8/% 9::0


*# % # "
" % #
# + " %
, %

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


Page 8 of 30

0 # %
" #

+ # % " ,
90# #
%
" # % "

public class AnotherWellbehavedClass {


SomeResource objRef;
// ...
protected void finalize() throws Throwable { // (1)
try { // (2)
if (objRef != null) objRef.close();
} finally { // (3)
super.finalize(); // (4)
}
}
}

Finalizer Chaining
? % " , B-%
.@-0 % " "
% # ,@0 "
finally ,
-0% #
try ,.0

2 " , % 0
%
< A this % #
" %
+ # %
% " #
% "

& :. " + 1
1 " " 1
,
/0 main() Blob %
< Blob ,
-0 Blob
,@0 " fat Blob
BasicBlob A ,
blobId0
,population0 6 Blob
,@0 +$ "Hello" finalize()
,
80 Blob + "Bye"
finalize() BasicBlob ,
.0%#
# # #
,:0# + "Bye"
# ,
/0

class BasicBlob { // (1)


static int idCounter;

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


Page 9 of 30

static int population;


protected int blobId;

BasicBlob() {
blobId = idCounter++;
++population;
}
protected void finalize() throws Throwable { // (2)
--population;
super.finalize();
}
}

class Blob extends BasicBlob { // (3)


int[] fat;

Blob(int bloatedness) { // (4)


fat = new int[bloatedness];
System.out.println(blobId + ": Hello");
}

protected void finalize() throws Throwable { // (5)


System.out.println(blobId + ": Bye");
super.finalize();
}
}

public class Finalizers {


public static void main(String[] args) { // (6)
int blobsRequired, blobSize;
try {
blobsRequired = Integer.parseInt(args[0]);
blobSize = Integer.parseInt(args[1]);
} catch(IndexOutOfBoundsException e) {
System.err.println(
"Usage: Finalizers <number of blobs> <blob size>");
return;
}
for (int i=0; i<blobsRequired; ++i) { // (7)
new Blob(blobSize);
}
System.out.println(BasicBlob.population + " blobs alive"); // (8)
}
}

! #

>java Finalizers 5 500000

# 3

0: Hello
1: Hello
2: Hello
0: Bye
1: Bye
2: Bye
3: Hello
4: Hello

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


Page 10 of 30

2 blobs alive

Invoking Garbage Collection


2 ) %
# A %
#

System.gc() A %
System.runFinalization() "
2 % Runtime
2) A Runtime
# )45 2
Runtime.getRuntime() Runtime

static Runtime getRuntime()

! Runtime #

void gc()

!A *# %
System.gc()

void runFinalization()

!A "
2 % System.runFinalization()

long freeMemory()

! , 0 )
45% #

long totalMemory()

! , 0 )
45
# #

& :- MemoryCheck
Finalizers & :. RunTime ,/0
)
45 ,
:0
,
70% ,
9D0
,
990 #
,
990 2 A ,
9.0
6 A # %
A # + #
System.gc() ,
9.0
%

!"#

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


Page 11 of 30

class BasicBlob { /* See Example 8.2. */ }


class Blob extends BasicBlob { /* See Example 8.2.*/ }

public class MemoryCheck {


public static void main(String[] args) { // (6)
int blobsRequired, blobSize;
try {
blobsRequired = Integer.parseInt(args[0]);
blobSize = Integer.parseInt(args[1]);
} catch(IndexOutOfBoundsException e) {
System.err.println(
"Usage: MemoryCheck <number of blobs> <blob size>");
return;
}
Runtime environment = Runtime.getRuntime(); // (7)
System.out.println("Total memory: " + environment.totalMemory());// (8)
System.out.println("Free memory before blob creation: "
+ environment.freeMemory()); // (9)
for (int i=0; i<blobsRequired; ++i) { // (10)
new Blob(blobSize);
}
System.out.println("Free memory after blob creation: "
+ environment.freeMemory()); // (11)
System.gc(); // (12)
System.out.println("Free memory after requesting GC: "
+ environment.freeMemory()); // (13)
System.out.println(BasicBlob.population + " blobs alive"); // (14)
}
}

! #

>java MemoryCheck 5 100000

# 3

Total memory: 2031616


Free memory before blob creation: 1773192
0: Hello
1: Hello
2: Hello
1: Bye
2: Bye
3: Hello
0: Bye
3: Bye
4: Hello
Free memory after blob creation: 818760
4: Bye
Free memory after requesting GC: 1619656
0 blobs alive

6 3

#
" '
# %
% #

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


Page 12 of 30

# # %
# " # %

'
2 # #
OutOfMemoryException #

Review Questions

< # delete

2 #

+ obj1 obj2, obj2


obj1% obj1 obj2

$ < % #

+ obj1 obj2 %
obj1

+ # # % #
arg1%

public class MyClass {


public static void main(String[] args) {
String msg;
String pre = "This program was called with ";
String post = " as first argument.";

String arg1 = new String((args.length > 0) ?


"'" + args[ 0 ] + "'" :
"<no argument>");
msg = arg1;
arg1 = null; // (1)
msg = pre + msg + post; // (2)
pre = null; // (3)

System.out.println(msg);

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


Page 13 of 30

msg = null; // (4)


post = null; // (5)
args = null; // (6)
}
}

2 ,
90

2 ,
.0

2 ,
-0

$ 2 ,
@0

2 ,
80

% 2 ,
B0

+ # finalize()
%

2 finalize()

< finalize()

$ finalize() #

# finalize()
finalize()

& E

# finalize()

finalize() # protected

2 finalize() # #

$ finalize()

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


Page 14 of 30

finalize()

'
" E

< #

finalize() #

2 #

$ + A B% A#
B

2 % %

8.2 Initializers
+ " " %
"

" % #
%# new

Field Initializer Expressions


+ " "
"
, -@% @/ BB% .BD0 # 1
"

class ConstantInitializers {
int minAge = 12; // (1) Non-static
static double pensionPoints = 10.5; // (2) Static
// ...

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


Page 15 of 30

" # " #
new + % ,90#
minAge " 12 ConstantInitializers #
new + " % , . @%
--0

6 " " #
" ,
.0# pensionPoints
" 10.5 # " 2 % " %

2 " 1
# this super "

# " % "
# % +
# % " ,
90 NO_OF_WEEKS
" ,
.0 5 #

class MoreInitializers {
int noOfDays = 7 * NO_OF_WEEKS; // (1) Non-static
static int NO_OF_WEEKS = 52; // (2) Static
// ...
}

+ " , B@% .880


" % final static

+ " " , . -% -90 2


" # "

Initializer Expression Execution in Textual Order

new % "
#

) A "
% "

" ? 1 "
1 1 % #
#

1 1 3 "
% %#
# !
"

+ % " ,
.0 1 %

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


Page 16 of 30

width " 1 1
width " ,
.0 1
# % width
,
@0 ,
.0 + %# # this
# ,
-0% # 0 width

class NonStaticInitializers {
int length = 10; // (1)
// double area = length * width; // (2) Not Ok. Illegal forward reference.
double area = length * this.width; // (3) Ok, but width has default value 0.
int width = 10; // (4)

int sqSide = height = 20; // (5) OK. Legal forward reference.


int height; // (6)
}

# ,
80 height " ,
80
1 " ,80
(sqSide = (height = 20)) & NonStaticInitializers #
height 20

1 1 A " #

& :@ # # " "


& :@ 5
" ,
.0 initMaxGuests()
,@0 *# %
occupancyPerRoom ,
-0# " ( % ,00#
initMaxGuests()%# #
# %
#

&! $ $ ($

class Hotel {
private int noOfRooms = 12; // (1)
private int maxNoOfGuests = initMaxGuests(); // (2) Bug
private int occupancyPerRoom = 2; // (3)

public int initMaxGuests() { // (4)


System.out.println("occupancyPerRoom: " +
occupancyPerRoom);
System.out.println("maxNoOfGuests: " +
noOfRooms * occupancyPerRoom);
return noOfRooms * occupancyPerRoom;
}

public int getMaxGuests() { // (5)


return maxNoOfGuests;
}

public int getOccupancy() { // (6)


return occupancyPerRoom;
}
}

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


Page 17 of 30

public class TestOrder {


public static void main(String[] args) {
Hotel hotel = new Hotel(); // (7)
System.out.println("After object creation: ");
System.out.println("occupancyPerRoom: " +
hotel.getOccupancy()); // (8)
System.out.println("maxNoOfGuests: " +
hotel.getMaxGuests()); // (9)
}
}

< 3

occupancyPerRoom: 0
maxNoOfGuests: 0
After object creation:
occupancyPerRoom: 2
maxNoOfGuests: 0

Initializer Expressions and Checked Exceptions

+ "
, 87% .D90 + #
" % "
"

& :8 "
" ,-0 createHotelPool() ,@0%#
TooManyHotelsException ,.0 + createHotelPool()
throws % #
try1catch % " ,-0%# %
*# % " #
%

" ,80 initMaxGuests() ,


B0%#
# RoomOccupancyTooHighException + # % #
main() C
RoomOccupancyTooHighException # #

' !

class RoomOccupancyTooHighException
extends RuntimeException {} // (1) Unchecked Exception
class TooManyHotelsException
extends Exception {} // (2) Checked Exception

class Hotel {
// Static Members
private static int noOfHotels = 12;
private static Hotel[] hotelPool = createHotelPool(); // (3)

private static Hotel[] createHotelPool() { // (4)


try {
if (noOfHotels > 10)
throw new TooManyHotelsException();

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


Page 18 of 30

} catch (TooManyHotelsException e) {
noOfHotels = 10;
System.out.println("No. of hotels adjusted to " +
noOfHotels);
}
return new Hotel[noOfHotels];
}
// Instance Members
private int noOfRooms = 215;
private int occupancyPerRoom = 5;
private int maxNoOfGuests = initMaxGuests(); // (5)

private int initMaxGuests() { // (6)


if (occupancyPerRoom > 4)
throw new RoomOccupancyTooHighException();
return noOfRooms * occupancyPerRoom;
}
}

public class ExceptionsInInitializers {


public static void main(String[] args) {
try { new Hotel();}
catch (RoomOccupancyTooHighException exception) {
exception.printStackTrace();
}
}
}

< 3

No. of hotels adjusted to 10


RoomOccupancyTooHighException
at Hotel.initMaxGuests(ExceptionsInInitializers.java:29)
at Hotel.<init>(ExceptionsInInitializers.java:25)
at ExceptionsInInitializers.main(ExceptionsInInitializers.java:36)

Static Initializer Blocks


) # " 2
% " "
# "

" # static #
# ,
-0

class StaticInitializers {

final static int ROWS = 12, COLUMNS = 10; // (1)


static long[][] matrix = new long[ROWS][COLUMNS]; // (2)
// ...
static { // (3) Static Initializer
for (int i = 0; i < matrix.length; i++)
for (int j = 0; j < matrix[i].length; j++)
matrix[i][j] = 2*i + j;
}
// ...
}

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


Page 19 of 30

StaticInitializers % final
,
90 " matrix " ,.0
% #
,-0

+ % "
, @9D% 9@:0

> " 2
" + " return
%

" % " "


+ %
" ,
90 ,
.0 " ,
-0

" " 3 #
this super "

# % "
1 1 & :B
# "
" 2 # ,
@0%#
sf1 2 ,
990 %
% # = # 1 #
# % # ,.0
%,80
% ,
/0 " 2
# " + %

)* ! $ + $ %

class StaticForwardReferences {

static { // (1) Static initializer block


sf1 = 10; // (2) OK. Assignment to sf1 allowed
// sf1 = if1; // (3) Not OK. Non-static field access in static context
// int a = 2 * sf1; // (4) Not OK. Read operation before declaration
int b = sf1 = 20; // (5) OK. Assignment to sf1 allowed
int c = StaticForwardReferences.sf1;// (6) OK. Not accessed by simple name
}

static int sf1 = sf2 = 30; // (7) Static field. Assignment to sf2 allowed
static int sf2; // (8) Static field
int if1 = 5; // (9) Non-static field

static { // (10) Static initializer block


int d = 2 * sf1; // (11) OK. Read operation after declaration
int e = sf1 = 50; // (12)
}

public static void main(String[] args) {


System.out.println("sf1: " + StaticForwardReferences.sf1);
System.out.println("sf2: " + StaticForwardReferences.sf2);
}
}

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


Page 20 of 30

< 3

sf1: 50
sf2: 30

& " "


3 # & :/ #
" ,
-0 try-catch ,
@0
2 " % %
"

& :/ # " ,
80 # ,
B0
" 2 #%
%

,* ! - # $

class BankrupcyException
extends RuntimeException {} // (1) Unchecked Exception
class TooManyHotelsException
extends Exception {} // (2) Checked Exception

class Hotel {
// Static Members
private static boolean bankrupt = true;
private static int noOfHotels = 11;
private static Hotel[] hotelPool;

static { // (3) Static block


try { // (4) Handles checked exception
if (noOfHotels > 10)
throw new TooManyHotelsException();
} catch (TooManyHotelsException e) {
noOfHotels = 10;
System.out.println("No. of hotels adjusted to " +
noOfHotels);
}
hotelPool = new Hotel[noOfHotels];
}

static { // (5) Static block


if (bankrupt)
throw new BankrupcyException(); // (6) Throws unchecked exception
}
// ...
}

public class ExceptionInStaticInitBlocks {


public static void main(String[] args) {
new Hotel();
}
}

< 3

No. of hotels adjusted to 10


Exception in thread "main" java.lang.ExceptionInInitializerError

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


Page 21 of 30

at ExceptionInStaticInitBlocks.main(ExceptionInStaticInitBlocks.java:33)
Caused by: BankrupcyException
at Hotel.<clinit>(ExceptionInStaticInitBlocks.java:26)

Instance Initializer Blocks


) " " static %)
" " +
%
" % # ,
.0 #

class InstanceInitializers {

long[] squares = new long[10]; // (1)


// ...
{ // (2) Instance Initializer
for (int i = 0; i < squares.length; i++)
squares[i] = i*i;
}
// ...
}

squares " ,
90% #
" ,.0 InstanceInitializers >
" 2
" % , "
0

2 " % " #
1 1 + & ::%
# ,
@0%# nsf1
,990 % % #
= # 1 # # % #
,
.0%,-0
%,80
% ,
/0

! ! $ + $ %

class NonStaticForwardReferences {

{ // (1) Instance initializer block


nsf1 = 10; // (2) OK. Assignment to nsf1 allowed
nsf1 = sf1; // (3) OK. Static field access in non-static context
// int a = 2 * nsf1; // (4) Not OK. Read operation before declaration
int b = nsf1 = 20; // (5) OK. Assignment to nsf1 allowed
int c = this.nsf1; // (6) OK. Not accessed by simple name
}

int nsf1 = nsf2 = 30; // (7) Non-static field. Assignment to nsf2 allowed
int nsf2; // (8) Non-static field
static int sf1 = 5; // (9) Static field

{ // (10) Instance initializer block


int d = 2 * nsf1; // (11) OK. Read operation after declaration
int e = nsf1 = 50; // (12)
}

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


Page 22 of 30

public static void main(String[] args) {


NonStaticForwardReferences objRef = new NonStaticForwardReferences();
System.out.println("nsf1: " + objRef.nsf1);
System.out.println("nsf2: " + objRef.nsf2);
}
}

< 3

nsf1: 50
nsf2: 30

" % # this super


" 2 # " % return
# "

2 " " #
#

2 " , /8% -D:0


%
# % " "
+ & :7% ,
90 " ,
.0
"

.! ! - # /

class Base {
protected int a;
protected int b;
void print() {
System.out.println("a: " + a);
}
}

class AnonymousClassMaker {
Base createAnonymous() {
return new Base() { // (1) Anonymous class
{ // (2) Instance initializer
a = 5; b = 10;
}
void print() {
super.print();
System.out.println("b: " + b);
}
}; // end anonymous class
}
}

public class InstanceInitBlock {


public static void main(String[] args) {
new AnonymousClassMaker().createAnonymous().print();
}
}

< 3

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


Page 23 of 30

a: 5
b: 10

& " " &


:9D # " ,
-0
try-catch ,
@0 2 " ,
80 #
,B0 %

& " "


# 3 "
% throws
" # %
" + " 3
#

0 1 $ ! ! - #

class RoomOccupancyTooHighException
extends Exception {} // (1) Checked exception
class BankrupcyException
extends RuntimeException {} // (2) Unchecked exception

class Hotel {
// Instance Members
private boolean bankrupt = true;
private int noOfRooms = 215;
private int occupancyPerRoom = 5;
private int maxNoOfGuests;

{ // (3) Instance block


try {
if (occupancyPerRoom > 4) // (4) Handles checked exception
throw new RoomOccupancyTooHighException();
} catch (RoomOccupancyTooHighException exception) {
System.out.println("ROOM OCCUPANCY TOO HIGH: " + occupancyPerRoom);
occupancyPerRoom = 4;
}
maxNoOfGuests = noOfRooms * occupancyPerRoom;
}

{ // (5) Instance initializer block


if (bankrupt)
throw new BankrupcyException(); // (6) Throws unchecked exception
} // ...
}

public class ExceptionsInInstBlocks {


public static void main(String[] args) {
new Hotel();
}
}

< 3

ROOM OCCUPANCY TOO HIGH: 5


Exception in thread "main" BankrupcyException

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


Page 24 of 30

at Hotel.<init>(ExceptionsInInstBlocks.java:26)
at ExceptionsInInstBlocks.main(ExceptionsInInstBlocks.java:32)

Constructing Initial Object State


< " #
new = % " , . @% --0
F
# A 1 F

# %
; 3

+ 6
, B-% .@-0

+ " "
"

& :99 " new ,:0


SubclassB SubclassB() ,
.0 this()
1 ,
-0 +
2 % ;
,
90 #
" ,@0 " ,
B0
1 ,
-0 = %
%

> "
# value ,
80
value 1 value #
" ,
80 value #
" ,B0
% 1 ,
-0

2 *

class SuperclassA {
public SuperclassA() { // (1)
System.out.println("Constructor in SuperclassA");
}
}
class SubclassB extends SuperclassA {

SubclassB() { // (2)
this(3);
System.out.println("Default constructor in SubclassB");
}

SubclassB(int i) { // (3)
System.out.println("Non-default constructor in SubclassB");
value = i;
}

{ // (4)
System.out.println("Instance initializer block in SubclassB");
value = 2; // (5)

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


Page 25 of 30

int value = initializerExpression(); // (6)

private int initializerExpression() { // (7)


System.out.println("Instance initializer expression in SubclassB");
return 1;
}
}

public class ObjectConstruction {


public static void main(String[] args) {
SubclassB objRef = new SubclassB(); // (8)
System.out.println("value: " + objRef.value);
}
}

< 3

Constructor in SuperclassA
Instance initializer block in SubclassB
Instance initializer expression in SubclassB
Non-default constructor in SubclassB
Default constructor in SubclassB
value: 3

# # 1 %
& :9. # #
"
this
%
" # #

# superValue ,
90 SuperclassA
" # SubclassB ,:0 SuperclassA
,
.0 doValue() ,-0 2 #
SuperclassA ,@0% SubclassB ,
/0
doValue() SubclassB ,-0
SuperclassA doValue() ,
@0
# SubclassB 5 #
% G
SubclassB " %
doValue ,-0 SubclassB
doValue() ,/0 SubclassB
value , 80 " ( %
"

! $ 2 *

class SuperclassA {
protected int superValue; // (1)
SuperclassA() { // (2)
System.out.println("Constructor in SuperclassA");
this.doValue(); // (3)
}
void doValue() { // (4)

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


Page 26 of 30

this.superValue = 911;
System.out.println("superValue: " + this.superValue);
}
}

class SubclassB extends SuperclassA {


private int value = 800; // (5)
SubclassB() { // (6)
System.out.println("Constructor in SubclassB");
this.doValue();
System.out.println("superValue: " + this.superValue);
}
void doValue() { // (7)
System.out.println("value: " + this.value);
}
}

public class ObjectInitialization {


public static void main(String[] args) {
System.out.println("Creating an object of SubclassB.");
new SubclassB(); // (8)
}
}

< 3

Creating an object of SubclassB.


Constructor in SuperclassA
value: 0
Constructor in SubclassB
value: 800
superValue: 0

6 "
2 " " + "
" "
"

+ " "
2 "
% "

Review Questions

) ' # %# "
E

public class MyClass {

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


Page 27 of 30

private static int count = 5;


final static int STEP = 10;
boolean alive;
// INSERT STATIC INITIALIZER BLOCK HERE
}

static { alive = true; count = 0; }

static { STEP = count; }

static { count += STEP; }

$ static ;

static {;}

% static { count = 1; }

, # # E

public class MyClass {


public static void main(String[] args) {
MyClass obj = new MyClass(l);
}
static int i = 5;
static int l;
int j = 7;
int k;

public MyClass(int m) {
System.out.println(i + ", " + j + ", " + k + ", " + l + ", " + m);
}
{ j = 70; l = 20; } // Instance Initializer Block
static { i = 50; } // Static Initializer Block
}

# % "

# % k# " #

# # # 50, 70, 0, 20, 0 #

$ # # # 50, 70, 0, 20, 20 #

# # # 5, 70, 0, 20, 0 #

% # # # 5, 7, 0, 20, 0 #

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


Page 28 of 30

' # %# "
# # # E

public class MyClass {


static int gap = 10;
double length;
final boolean active;

// INSERT CODE HERE


}

instance { active = true; }

MyClass { gap += 5; }

{ gap = 5; length = (active ? 100 : 200) + gap; }

$ { ; }

{ length = 4.2; }

% { active = (gap > 5); length = 5.5 + gap;}

. # # E

public class Initialization {


private static String msg(String msg) {
System.out.println(msg); return msg;
}

public Initialization() { m = msg("1"); }

{ m = msg("2"); }

String m = msg("3");

public static void main(String[] args) {


Object obj = new Initialization();
}
}

# # # 1%2% 3#

# # # 2%3% 1#

$ # # # 3%1% 2#

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


Page 29 of 30

# # # 1%3% 2#

0 # # E

public class Initialization {


private static String msg(String msg) {
System.out.println(msg); return msg;
}

static String m = msg("1");

{ m = msg("2"); }

static { m = msg("3"); }

public static void main(String[] args) {


Object obj = new Initialization();
}
}

# # # 1%2% 3#

# # # 2%3% 1#

$ # # # 3%1% 2#

# # # 1%3% 2#

#
// # E

class GeomInit {
// int width = 14; /* Line A */
{
// area = width * height; /* Line B */
}
int width = 37;
{
// height = 11; /* Line C */
}
int height, area;
// area = width * height; /* Line D */
{
// int width = 15; /* Line E */
area = 100;
}
};

# #

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


Page 30 of 30

$ $

&

Chapter Summary

# # 3

% #

"

" % " "

" " % %

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

You might also like