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
+
,
#
6
#
%# % 70 2
) 45 )
1 ) 45%
& 88
# 2
#
%
9:9 #
; < %
% %
2
# %
# ,9
#
# + %
"
=
0 .
:9 +
#
#
#
# # #
%#
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
%
% o8%o10%o11% < o8 o10
<
% o9
% , o9
o5%o6% <
o7
0 % %
o11
% %05%
<
o11
# ? #
%
# #
%#
"
,
-.@0 %
) " +
% ?
,
0 #
2 %
# #
# #
# #
#
; SoftReference% ,
java.lang.ref.Reference WeakReference%PhantomReference0 ,
02
% # %#
Facilitating Garbage Collection # #
+#
%
2
%
% "
#
2
6
%
% #
try-catch-finally % # #
"
,
8/%
+ 9::0
%
finally
%
#
% #
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 // ... } // ... } +
% # "
, 90
null
, .0 %
%
A
#
%
+
#
%
! % & :9 HeavyItem & finalize() #
#
6
# HeavyItem Object #
%
# + $# ,
# #
"
RecyclingBin :9% HeavyItem , 80 % itemA , B0 % # +
" -.@0
HeavyItem
% + &
%
HeavyItem createHeavyItem() HeavyItem
file://C:\Documents and Settings\cdot\Local Settings\Temp\~hhC01A.htm
, @0 + , B0
6/16/2006
Page 6 of 30
+ &
:9%
RecyclingBin item1%# HeavyItem % 2 %
createList()
+
, /0 + HeavyItem
% ,
class HeavyItem { int[] itemBody; String itemID; HeavyItem nextItem;
0
// (1)
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) { // HeavyItem itemA = new HeavyItem(itemID + " local item", null); // itemA = new HeavyItem(itemID, null); // System.out.println("Return from creating HeavyItem " + itemID); return itemA; // }
(4) (5) (6)
public static HeavyItem createList(String listID) { HeavyItem item3 = new HeavyItem(listID + ": item3", null); HeavyItem item2 = new HeavyItem(listID + ": item2", item3); HeavyItem item1 = new HeavyItem(listID + ": item1", item2); System.out.println("Return from creating list " + listID); return item1; }
// // // //
(8) (9) (10) (11)
public static void main(String[] args) { HeavyItem list = createList("X"); list = createList("Y");
// (13) // (14) // (15)
HeavyItem itemOne = createHeavyItem("One"); HeavyItem itemTwo = createHeavyItem("Two"); itemOne = null; createHeavyItem("Three"); createHeavyItem("Four"); System.out.println("Return from main().");
(7)
// (12)
// // // // //
(16) (17) (18) (19) (20)
} } 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 Return from creating HeavyItem Return from creating HeavyItem Three local item: recycled. Three: recycled. Two local item: recycled. Return from creating HeavyItem One local item: recycled. One: recycled. Return from main().
One Two Three
Four
main() + & :9% , 9-0 createHeavyItem() createList() + X , 980 % Y list% main() main() itemOne itemTwo% One # , 970 , .D0
#
RecyclingBin X , 9@0 % , 980 1
, 9B0
, 9/0 % itemOne # HeavyItem %#
HeavyItem , 9:0 % createHeavyItem() %
< list0 #
1 HeavyItem #
HeavyItem # main() Four Five #
Two , 2
Y, itemTwo0 #
% , 970
, .D0 %
2
Object Finalization <
" finalize() finalize() Object protected void finalize() throws Throwable
2
2
finalize() "
2 *#
Object
" %
%
%
#
# "
#
,
% +
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 { try { if (objRef != null) objRef.close(); } finally { super.finalize(); } } }
// (1) // (2) // (3) // (4)
Finalizer Chaining ? .@-0
% %
finally try 2
# , -0 % , .0
% " , @0
"
B-%
#
" <
, " "
, % this
A
0 % %
#
"
% +
# %
% " #
%
&
:. 1
" , /0
" " main()
"
+
< fat , @0 " BasicBlob population0 , , @0 + $ Blob , 80 finalize() BasicBlob # # # , :0# +
1 1 %
Blob Blob A 6 +
, -0
blobId0 , Blob "Hello" finalize() "Bye"
, .0 %# "Bye"
#
class BasicBlob { static int idCounter;
Blob Blob
, /0
// (1)
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 { --population; super.finalize(); }
// (2)
} class Blob extends BasicBlob { int[] fat;
// (3)
Blob(int bloatedness) { fat = new int[bloatedness]; System.out.println(blobId + ": Hello"); }
// (4)
protected void finalize() throws Throwable { System.out.println(blobId + ": Bye"); super.finalize(); }
// (5)
} 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 "); return; } for (int i=0; i
#
>java Finalizers 5 500000 # 0: 1: 2: 0: 1: 2: 3: 4:
3
Hello Hello Hello Bye Bye Bye Hello 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
%
# A
System.gc() System.runFinalization() 2 2) # ) 45 2 Runtime.getRuntime()
% " Runtime
% Runtime
A Runtime
static Runtime getRuntime() !
#
Runtime
void gc() !A
*#
%
System.gc() void runFinalization() !A 2 %
" System.runFinalization()
long freeMemory() !
,
0
) 45%
#
long totalMemory() !
,
0
) 45 #
&
:Finalizers
#
MemoryCheck &
:.
RunTime ) 45
, 70 %
, 9D0 , 990
# , 990 2 A A #
6 A System.gc()
, /0 , :0
# , 9.0 %
+
, 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 "); return; } Runtime environment = Runtime.getRuntime(); // System.out.println("Total memory: " + environment.totalMemory());// System.out.println("Free memory before blob creation: " + environment.freeMemory()); // for (int i=0; i
(7) (8) (9) (10)
(11) (12) (13) (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
E # <
#
2
delete
#
+ obj1%
obj1 obj1
obj2,
obj2
obj2
$ <
% #
+ obj1 + arg1%
obj1
%
obj2
#
#
%
#
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; post = null; args = null;
// (4) // (5) // (6)
} } # 2
, 90
2
, .0
2
, -0
$ 2
, @0
2
, 80
% 2
, B0 E #
+
#
finalize()
% 2
finalize()
< $
finalize() #
finalize() #
finalize() finalize()
&
E # #
finalize() 2
$
finalize()
finalize()
#
protected #
#
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 "
minAge new --0 6
# +
" # % , 90# ConstantInitializers % ,
12
+
"
" " "
2
" , .0# " 2
10.5 #
" #
pensionPoints " %
%
"
super
#
"
%
"
% #
%
" "
, .0
5
// (1) Non-static // (2) Static
" "
, B@% final static
%
"
" "
+ NO_OF_WEEKS #
, 90
class MoreInitializers { int noOfDays = 7 * NO_OF_WEEKS; static int NO_OF_WEEKS = 52; // ... }
+
#
1 this
#
+
# . @%
#
,
. -%
.880
-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 width , @0 #
, -0 %
1
1
, .0
1 % , .0 + 0
#
class NonStaticInitializers { int length = 10; // double area = length * width; double area = length * this.width; int width = 10; int sqSide = height = 20; int height;
// // // //
%# width
#
width this
(1) (2) Not Ok. Illegal forward reference. (3) Ok, but width has default value 0. (4)
// (5) OK. Legal forward reference. // (6)
} #
, 80
height " " , 80 NonStaticInitializers #
1 (sqSide = (height = 20)) & height 20 1
&
:@
# # &
1
A
"
"
#
"
:@
5 "
, @0 occupancyPerRoom
, 80
, -0# initMaxGuests()%#
, .0
initMaxGuests() *# % 00# % ,
" ( #
#
% #
&! class Hotel private private private
$
$
{ int noOfRooms = 12; int maxNoOfGuests = initMaxGuests(); int occupancyPerRoom = 2;
($ // (1) // (2) Bug // (3)
public int initMaxGuests() { // (4) System.out.println("occupancyPerRoom: " + occupancyPerRoom); System.out.println("maxNoOfGuests: " + noOfRooms * occupancyPerRoom); return noOfRooms * occupancyPerRoom; } public int getMaxGuests() { return maxNoOfGuests; }
// (5)
public int getOccupancy() { return occupancyPerRoom; }
// (6)
}
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 TooManyHotelsException
throws try1catch % *# % %
"
" createHotelPool() , .0 + % , -0 %#
"
, @0 %# createHotelPool() # % #
"
initMaxGuests() , 80 RoomOccupancyTooHighException + # % main() C RoomOccupancyTooHighException # # #
'
, B0 %# #
!
class RoomOccupancyTooHighException extends RuntimeException {} class TooManyHotelsException extends Exception {}
// (1) Unchecked Exception // (2) Checked Exception
class Hotel { // Static Members private static int noOfHotels = 12; private static Hotel[] hotelPool = createHotelPool(); private static Hotel[] createHotelPool() { try { if (noOfHotels > 10) throw new TooManyHotelsException();
file://C:\Documents and Settings\cdot\Local Settings\Temp\~hhC01A.htm
// (3) // (4)
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 private int private int private int
Members noOfRooms = 215; occupancyPerRoom = 5; 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.(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 " , -0
, 90
+
% @9D%
, > "
" +
"
matrix
final , .0 %
#
" 9@:0 2
"
return
% " %
"
" +
"
, 90
, .0
" "
this
"
#
% 1
#
#
" &
1
#
% %
3
"
super
"
% , -0
:B
"
2 # sf1 # = # # , .0 %, 80 % #
)*
, @0 %# 2 , 990
% 1
, /0
!
" "
$
+
# 2 %
+
$
%
class StaticForwardReferences { static { sf1 = // sf1 = // int a int b int c }
// (1) Static initializer block 10; // (2) OK. Assignment to sf1 allowed if1; // (3) Not OK. Non-static field access in static context = 2 * sf1; // (4) Not OK. Read operation before declaration = sf1 = 20; // (5) OK. Assignment to sf1 allowed = StaticForwardReferences.sf1;// (6) OK. Not accessed by simple name
static int sf1 = sf2 = 30; static int sf2; int if1 = 5;
// (7) Static field. Assignment to sf2 allowed // (8) Static field // (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
2
"
%
" :/ # try-catch
, @0
% "
&
:/
# " %
,*
"
, 80 #%
2
!
-
#
#
, B0
$
class BankrupcyException extends RuntimeException {} class TooManyHotelsException extends Exception {}
// (1) Unchecked Exception // (2) Checked Exception
class Hotel { // Static Members private static boolean bankrupt = true; private static int noOfHotels = 11; private static Hotel[] hotelPool; static { try {
// (3) Static block // (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 { if (bankrupt) throw new BankrupcyException(); } // ...
// (5) Static block // (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.(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 , .0 " %
"
, 90 % # InstanceInitializers 2 "
,
>
0 2
"
% 1 , @0 %# , 990
# = # , .0 %, -0 %, 80 %
" + &
1
1
#
# ::% % #
%
nsf1 % # #
, /0
!
!
$
+
$
%
class NonStaticForwardReferences { {
//
nsf1 = 10; nsf1 = sf1; int a = 2 * nsf1; int b = nsf1 = 20; int c = this.nsf1;
// // // // // //
(1) (2) (3) (4) (5) (6)
Instance initializer block OK. Assignment to nsf1 allowed OK. Static field access in non-static context Not OK. Read operation before declaration OK. Assignment to nsf1 allowed OK. Not accessed by simple name
} int nsf1 = nsf2 = 30; int nsf2; static int sf1 = 5; {
// (7) Non-static field. Assignment to nsf2 allowed // (8) Non-static field // (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 "
%
# 2
# 2 #
" "
this
"
super "
%
"
return
#
# 2 # + &
" %
,
/8% "
:7%
, 90
"
-D:0 % " , .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 # try-catch , B0
"
"
" , @0 2
" %
&
, 80
#
" #
"
3
" throws
% " " #
&
, -0
#
+
%
"
0
3
1
$
!
class RoomOccupancyTooHighException extends Exception {} class BankrupcyException extends RuntimeException {}
!
-
#
// (1) Checked exception // (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.(ExceptionsInInstBlocks.java:26) at ExceptionsInInstBlocks.main(ExceptionsInInstBlocks.java:32)
Constructing Initial Object State <
" =
new
% A
#
# , F
" 1
. @%
# ;
--0 F
%
3
+
6 ,
+
B-%
"
.@-0
" "
&
:99 SubclassB
"
new SubclassB() , -0 +
1 2
%
, 90 , @0
" 1
, :0 this()
, .0
;
# " , -0
, B0 =
%
% >
" # 1
value "
value
, 80 value
" , B0 %
2
, 80
value 1
#
# , -0
*
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 % "
# # #
, 90
SuperclassA SuperclassA " # , :0 doValue() , .0 , -0 2 # SuperclassA SubclassB , @0 % , /0 doValue() SubclassB , -0 SuperclassA doValue() , @0 SubclassB # 5 # % G SubclassB " % doValue SubclassB , -0 doValue() SubclassB , /0 value , 80 " ( % "
!
superValue SubclassB
$
2
*
class SuperclassA { protected int superValue; SuperclassA() { System.out.println("Constructor in SuperclassA"); this.doValue(); } void doValue() {
// (1) // (2) // (3) // (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 Constructor value: 0 Constructor value: 800 superValue: 6
object of SubclassB. in SuperclassA in SubclassB 0
" 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
# 0
#
#
1%3%
#
2#
#
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#
# #
//
class GeomInit { // int width = 14; { // area = width * height; } int width = 37; { // height = 11; } int height, area; // area = width * height; { // int width = 15; area = 100; } }; #
E
/* Line A */ /* Line B */
/* Line C */
/* Line D */ /* Line E */
#
file://C:\Documents and Settings\cdot\Local Settings\Temp\~hhC01A.htm
6/16/2006
Page 30 of 30
2
6 $
$ &
Chapter Summary
#
#
3 %
#
" "
"
"
%
"
%
"
%
file://C:\Documents and Settings\cdot\Local Settings\Temp\~hhC01A.htm
6/16/2006