Chapter 4.
Declarations and Access Control
Exam Objectives
Write code that declares, constructs, and initializes arrays of any base type using
any of the permitted forms, both for declaration and for initialization.
Declare classes, inner classes, methods, instance variables, static variables and
automatic (method local) variables, making appropriate use of all permitted
modifiers (such as public, final, static, abstract). State the significance of
each of these modifiers both singly and in combination, and state the effect of
package relationships on declared items qualified by these modifiers.
o For nested classes, see Chapter 7.
or a given class, determine if a default constructor !ill be created, and if so, state
the prototype of that constructor.
"dentify the legal return types for any method, given the declarations of all related
methods in this or parent classes.
o For method overriding, see Section 6.2.
Supplementary Objectives
Define and use anonymous arrays.
#nderstand usage of this reference in instance methods.
#nderstand the term method signature and state the circumstances under !hich
methods can be overloaded.
"dentify a non$default constructor, and understand ho! constructors can be
overloaded.
State ho! the package and import statements are used to define packages and
import from packages.
4.1 Arrays
%n array is a data structure that defines an inde&ed collection of a fi&ed number of homogeneous
data elements. 'his means that all elements in the array have the same data type. % position in the
array is indicated by a non$negative integer value called the index. %n element at a given position
in the array is accessed using the inde&. 'he size of an array is fi&ed and cannot increase to
accommodate more elements.
"n (ava, arrays are ob)ects. %rrays can be of primitive data types or reference types. "n the former
case, all elements in the array are of a specific primitive data type. "n the latter case, all elements
are references of a specific reference type. *eferences in the array can then denote ob)ects of this
reference type or its subtypes. +ach array ob)ect has a final field called length, !hich specifies
the array size, that is, the number of elements the array can accommodate. 'he first element is
al!ays at inde& , and the last element at inde& n$-, !here n is the value of the length field in the
array.
Simple arrays are one-dimensional arrays, that is, a simple sequence of values. Since arrays can
store ob)ect references, the ob)ects referenced can also be array ob)ects. 'his allo!s
implementation of array of arrays.
.assing array references as parameters is discussed in Section /.0,. 'ype conversions for array
references on assignment and method invocation are discussed in Section 1.1.
Declaring Array ariables
%n array variable declaration has either the follo!ing synta&2
<element type[] <array name;
or
<element type <array name[];
!here <element type can be a primitive data type or a reference type. 'he array variable <array
name has the type <element type[]. 3ote that the array size is not specified. 'his means that
the array variable <array name can be assigned an array of any length, as long as its elements
have <element type.
"t is important to understand that the declaration does not actually create an array. "t only declares
a reference that can denote an array ob)ect.
int anIntArray[], oneInteger;
Pizza[] mediumPizzas, largePizzas;
'hese t!o declarations declare anIntArray and mediumPizzas to be reference variables that can
denote arrays of int values and arrays of Pizza ob)ects, respectively. 'he variable largePizzas
can denote an array of pizzas, but the variable oneInteger cannot denote an array of int values4
it is simply an int variable.
When the [] notation follo!s the type, all variables in the declaration are arrays. 5ther!ise the []
notation must follo! each individual array name in the declaration.
%n array variable that is declared as a member of a class, but is not initialized to denote an array,
!ill be initialized to the default reference value null. 'his default initialization does not apply to
local reference variables and, therefore, does not apply to local array variables either (see Section
0.6, p. //). 'his should not be confused !ith initialization of the elements of an array during array
construction.
Constructing an Array
%n array can be constructed for a specific number of elements of the element type, using the new
operator. 'he resulting array reference can be assigned to an array variable of the corresponding
type.
<array name = new <element type [<array si!e];
'he minimum value of <array si!e is (i.e., arrays !ith zero elements can be constructed in
(ava). "f the array size is negative, a !egati"eArray#ize$%ception is thro!n.
7iven the follo!ing array declarations2
int anIntArray[], oneInteger;
Pizza[] mediumPizzas, largePizzas;
the arrays can be constructed as follo!s2
anIntArray = new int[&]; '' array for & integers
mediumPizzas = new Pizza[(]; '' array of ( pizzas
largePizzas = new Pizza[)]; '' array of ) pizzas
'he array declaration and construction can be combined.
<element type
&
[] <array name = new <element type
*
[<array si!e];
8o!ever, here array type <element type
*
[] must be assigna"le to array type <element type
&
[]
(see Section 1.1, p. 01,). When the array is constructed, all its elements are initialized to the
default value for <element type
*
. 'his is true for both member and local arrays !hen they are
constructed.
"n all the e&les belo!, the code constructs the array and the array elements are implicitly
initialized to their default value. or e&le, the element at inde& * in array anIntArray gets the
value , and the element at inde& ) in array mediumPizzas gets the value null !hen the arrays
are constructed.
int[] anIntArray = new int[&]; '' +efault element "alue, -
Pizza[] mediumPizzas = new Pizza[(]; '' +efault element "alue, null-
'' Pizza class e%tends .b/ect class
.b/ect ob/Array = new Pizza[)]; '' +efault element "alue, null-
'' Pizza class implements $atable interface
$atable[] eatables = new Pizza[*]; '' +efault element "alue, null-
'he value of the field length in each array is set to the number of elements specified during the
construction of the array9 for e&le, medium Pizzas-length has the value (.
5nce an array has been constructed, its elements can also be e&plicitly initialized individually9 for
e&le, in a loop. +&les in the rest of this section make heavy use of a loop to traverse
through the elements of an array for various purposes.
!nitiali"ing an Array
(ava provides the means of declaring, constructing, and e&plicitly initializing an array in one
declaration statement2
<element type[] <array name = 0 <array initiali!e list 1;
'his form of initialization applies to member as !ell as local arrays. 'he <array initiali!e list is a
comma$separated list of zero or more e&pressions. Such an array initialization block results in the
construction and initialization of the array.
int[] anIntArray = 0&, ), 23, *, 4, 5, &(, *, &, (1;
'he array anIntArray is declared as an array of ints. "t is constructed to hold -, elements (equal
to the length of the list of e&pressions in the block), !here the first element is initialized to the
value of the first e&pression (&6, the second element to the value of the second e&pression ()6,
and so on.
'' Pizza class e%tends .b/ect class
.b/ect[] ob/Array = 0 new Pizza76, new Pizza76, null 1;
'he array ob/Array is declared as an array of the .b/ect class, constructed to hold three
elements. 'he initialization code sets the first t!o elements of the array to refer to t!o Pizza
ob)ects, !hile the last element is initialized to the null reference. 3ote that the number of ob)ects
created in the above declaration statement is actually three2 the array ob)ect !ith three references
and the t!o Pizza ob)ects.
'he e&pressions in the <array initiali!e list are evaluated from left to right, and the array name
obviously cannot occur in any of the e&pressions in the list. "n the e&les above, the <array
initiali!e list is terminated by the right curly bracket, 1, of the block. 'he list can also be legally
terminated by a comma. 'he follo!ing array has length t!o, not three2
8opping[] pizza8oppings = 0 new 8opping79cheese96, new 8opping79tomato96, 1;
'he declaration statement at (-) in the follo!ing code defines an array of four #tring ob)ects,
!hile the declaration statement at (0) should make it clear that a #tring ob)ect is not the same as
an array of char.
'' Array with 2 #tring ob/ects
#tring[] pets = 09crocodiles9, 9elephants9, 9crocophants9, 9elediles91; '' 7&6
'' Array of ) characters
char[] charArray = 0:a:, :h:, :a:1; '' 7*6 !ot the same as 9aha9-
#sing an Array
'he !hole array is referenced by the array name, but individual array elements are accessed by
specifying an inde& !ith the [] operator. 'he array element access e&pression has the follo!ing
synta&2
<array name [<index expression]
+ach individual element is treated as a simple variable of the element type. 'he index is specified
by the <index expression, !hich can be any e&pression that evaluates to an non$negative int
value. Since the lo!er bound of an array is al!ays , the upper bound is one less than the array
size, that is, (<array name-length;&). 'he ith element in the array has inde& 7i;&6. %t runtime,
the inde& value is automatically checked to ensure that it is !ithin the array inde& bounds. "f the
inde& value is less than or greater than or equal to <array name.length in an array element
access e&pression, an ArrayInde%.ut.f<ounds$%ception is thro!n. % program can either check
the inde& e&plicitly or catch the e&ception (see Section :.:, p. -;-), but an illegal inde& is typically
an indication of a program bug.
"n the array element access e&pression, the <array name can, in fact, be any e&pression that
returns a reference to an array. or e&le, the follo!ing e&pression accesses the element !ith
the inde& - in the character array returned by a call to the to=harArray76 method of the #tring
class2 9A>A9-to=harArray76[&].
'he array operator [] is used to declare array types (8opping[]), specify array size (new
8oppings[)]), and to access array elements (toppings[&]). 'his operator is not used !hen the
array reference is manipulated, for e&le in an array reference assignment (see Section 1.1, p.
01,) or !hen the array reference is passed as an actual parameter in a method call (see Section
/.0,, p. <-).
+&le 6.- sho!s traversal of arrays. 'he loop at (/) initializes the local array trialArray
declared at (0) five times !ith pseudo$random numbers (from - to &-), by calling the method
randomize76 at (:). 'he minimum value in the array is found by calling the method
find?inimum76 at (1), and is stored in the array store?inimum declared at (-). 'he loop at (6)
prints the minimum values from the trials. 'he start value of the loop variable is initially set to .
'he loop condition tests !hether the loop variable is less than the length of the array9 this
guarantees that the inde& !ill not go out of bounds.
Example 4.1 Using Arrays
class 8rials 0
public static "oid main7#tring[] args6 0
'' +eclare and construct the local arrays
double[] store?inimum = new double[(]; '' 7&6
double[] trialArray = new double[&(]; '' 7*6
for 7int i = ; i @ store?inimum-length; AAi6 0 '' 7)6
'' Initialize the array
randomize7trialArray6;
'' Bind and store the minimum "alue
store?inimum[i] = find?inimum7trialArray6;
1
'' Print the minimum "alues 726
for 7int i = ; i @ store?inimum-length; AAi6
#ystem-out-println7store?inimum[i]6;
1
public static "oid randomize7double[] "alArray6 0 '' 7(6
for 7int i = ; i @ "alArray-length; AAi6
"alArray[i] = ?ath-random76 C &-;
1
public static double find?inimum7double[] "alArray6 0 '' 746
'' Assume the array has at least one element-
double minDalue = "alArray[];
for 7int i = &; i @ "alArray-length; AAi6
minDalue = ?ath-min7minDalue, "alArray[i]6;
return minDalue;
1
1
.ossible output from the program2
4-5(43)&)&3E(2E
(-)424)&33)2&)4)
E-)(32&**3E2*34
E-E(E*5*E2E*(E&3
3-5(33((34&3E23
Anonymous Arrays
%s sho!n earlier in this section, the follo!ing declaration statement
<element type
&
[] <array name = new <element type
*
[<array si!e]; '' 7&6
int[] intArray = new int[(];
can be used to construct arrays using an array creation e&pression. 'he size of the array is
specified in the array creation e&pression, !hich creates the array and initializes the array elements
to their default values. 5n the other hand, the follo!ing declaration statement
<element type[] <array name = 0 <array initiali!e list 1; '' 7*6
int[] intArray = 0), (, *, E, 41;
both creates the array and initializes the array elements to specific values given in the array
initializer block. 8o!ever, the array initialization block is not an e&pression.
(ava has another array creation e&pression, called anonymous array, !hich allo!s the concept of
the array creation e&pression from (-) and the array initializer block from (0) to be combined, to
create and initialize an array ob)ect2
new <element type[] 0 <array initiali!e list 1
new int[] 0), (, *, E, 41
'he construct has enough information to create a nameless array of a specific type. 3either the
name of the array nor the size of the array is specified. 'he construct returns an array reference
that can be assigned and passed as parameter. "n particular, the follo!ing t!o e&les of
declaration statements are equivalent.
int[] intArray = 0), (, *, E, 41; '' 7&6
int[] intArray = new int[] 0), (, *, E, 41; '' 7*6
"n (-), an array initializer block is used to create and initialize the elements. "n (0), an anonymous
array e&pression is used. "t is tempting to use the array initialization block as an e&pression9 for
e&le, in an assignment statement as a short cut for assigning values to array elements in one
go. 8o!ever, this is illegal4instead, an anonymous array e&pression should be used.
int[] daysIn?onth;
daysIn?onth = 0)&, *E, )&, ), )&, ), )&, )&, ), )&, ), )&1; '' !ot ok-
daysIn?onth = new int[] 0)&, *E, )&, ), )&, ), )&, )&, ), )&, ), )&1; '' ok-
'he concept of anonymous arrays is similar to that of anonymous classes (see Section =.:, p. /,;)2
they both combine the definition and instantiation of classes into one process.
"n +&le 6.0, an anonymous array is constructed at (-) and passed as parameter to the static
method find?inimum76 defined at (0). 3ote that no array name or array size is specified for the
anonymous array.
Example 4.2 Using Anonymous Arrays
class AnonArray 0
public static "oid main7#tring[] args6 0
#ystem-out-println79?inimum "alue, 9 A
find?inimum7new int[] 0), (, *, E, 4166; '' 7&6
1
public static int find?inimum7int[] data#eF6 0 '' 7*6
'' Assume the array has at least one element-
int min = data#eF[];
for 7int inde% = &; inde% @ data#eF-length; AAinde%6
if 7data#eF[inde%] @ min6
min = data#eF[inde%];
return min;
1
1
5utput from the program2
?inimum "alue, *
$ultidimensional Arrays
Since an array element can be an ob)ect reference and arrays are ob)ects, array elements can
themselves reference other arrays. "n (ava, an array of arrays can be defined as follo!s2
<element type[][]---[] <array name;
or
<element type <array name[][]---[];
"n fact, the sequence of square bracket pairs, [], indicating the number of dimensions, can be
distributed as a postfi& to both the element type and the array name. %rrays of arrays are also
sometimes called multidimensional arrays.
'he follo!ing declarations are all equivalent2
int[][] mGnArray; '' *;dimensional array
int[] mGnArray[]; '' *;dimensional array
int mGnArray[][]; '' *;dimensional array
"t is customary to combine the declaration !ith the construction of the multidimensional array.
int[][] mGnArray = new int[2][(]; '' 2 % ( matri% of ints
'he previous declaration constructs an array mGnArray of four elements, !here each element is an
array (ro!) of ( int values. 'he concept of ro!s and columns is often used to describe the
dimensions of a 0$dimensional array, !hich is often called a matrix. 8o!ever, such an
interpretation is not dictated by the (ava language.
+ach ro! in the previous matri& is denoted by mGnArray[i], !here i > 2- +ach element in the
i
th
ro!, mGnArray[i], is accessed by mGnArray[i][/], !here / > (- 'he number of ro!s is
given by mGnArray-length, in this case 2, and the number of values in the i
th
ro! is given by
mGnArray[i]-length, in this case ( for all the ro!s, !here i > 2.
?ultidimensional arrays can also be constructed and e&plicitly initialized using array initializer
blocks discussed for simple arrays. 3ote that each ro! is an array !hich uses an array initializer
block to specify its values2
double[][] identity?atri% = 0
0&-, -, -, - 1, '' &- row
0-, &-, -, - 1, '' *- row
0-, -, &-, - 1, '' )- row
0-, -, -, &- 1 '' 2- row
1; '' 2 % 2 Bloating;point matri%
%rrays in a multidimensional array need not have the same length. 'he array of arrays
pizzaHalore in the code belo! !ill have five ro!s, the first four ro!s have different lengths but
the fifth ro! is left unconstructed.
Pizza[][] pizzaHalore = 0
0 new Pizza76, null, new Pizza76 1, '' &- row is an array of ) elements-
0 null, new Pizza761, '' *- row is an array of * elements-
new Pizza[&], '' )- row is an array of & element-
01, '' 2- row is an array of elements-
null '' (- row is not constructed-
1;
When constructing multidimensional arrays !ith the new operator, the length of the deeply nested
arrays may be omitted. "n this case, these arrays are left unconstructed. or e&le an array of
arrays to represent a room on a floor in a hotel on a street in a city can have the type >otelIoom[]
[][][]. rom left to right, the square brackets represent indices for street, hotel, floor, and room,
respectively. 'his 6$dimensional array of arrays can be constructed piecemeal, starting !ith the
leftmost dimension and proceeding to the rightmost.
>otelIoom[][][][] rooms = new >otelIoom[&][(][][]; '' Just streets and hotels-
'he above declaration constructs the array of arrays rooms partially !ith ten streets, !here each
street has five hotels. loors and rooms can be added to a particular hotel on a particular street2
rooms[][] = new >otelIoom[)][]; '' ) floors in &st- hotel on &st- street-
rooms[][][] = new >otelIoom[E]; '' E rooms on &st- floor in this hotel-
rooms[][][][] = new >otelIoom76; '' Initialize &st- room on this floor-
'he code belo! constructs an array of arrays matri%, !here the first ro! has one element, the
second ro! has t!o elements, and the third ro! has three elements. 3ote that the outer array is
constructed first. 'he second dimension is constructed in a loop that constructs the array in each
ro!. 'he elements in the multidimensional array !ill be implicitly initialized to the default double
value (-+). "n igure 6.-, the array of arrays matri% is depicted after the elements have been
e&plicitly initialized.
double[][] matri% = new double[)][]; '' !o- of rows-
for 7int i = ; i @ matri%-length; AAi6
matri%[i] = new double[i A &]; '' =onstruct a row-
Figure 4.1. Array of Arrays
'!o other !ays of initializing such an array of arrays, the first one using array initializer blocks and
the second one using an anonymous array of arrays are sho!n as follo!s2
double[][] matri%* = 0
0-1, '' &- row
0-, -1, '' *- row
0-, -, -1 '' )- row
1
double[][] matri%) = new double[][] 0
0-1, '' &- row
0-, -1, '' *- row
0-, -, -1 '' )- row
1
'he type of variable matri% is double[][] (i.e., a t!o$dimensional array of double values). 'he
type of variable matri%[i] (!here i> matri%-length) is double[] (i.e., a one$dimensional
array of double values). 'he type of variable matri%[i][/] (!here i> matri%-length and
/> matri%[i]-length) is double (i.e., a simple variable of type double6.
3ested loops are a natural match for manipulating multidimensional arrays. "n +&le 6./, a
rectangular 6 & / int matri& is declared and constructed at (-). 'he program finds the minimum
value in the matri&. 'he outer loop at (0) traverses the ro!s (mGnArray[i], i>
mGnArray-length), and the inner loop at (/) traverses the elements in each ro! in turn
(mGnArray[i][/], /> mGnArray[i]-length). 'he outer loop is e&ecuted mGnArray-length
times, or 6 times, and the inner loop is e&ecuted (mGnArray-length) & (mGnArray[i]-length), or
-0 times, since all ro!s have the same length, /.
Example 4.3 Using Multidimensional Arrays
class ?ultiArrays 0
public static "oid main7#tring[] args6 0
'' +eclare and construct the ? G ! matri%-
int[][] mGnArray = 0 '' 7&6
0&4, 5, &*1, '' &- row
0 3, *, &E1, '' *- row
0&2, &&, (1, '' )- row
0 E, (, &1 '' 2- row
1; '' 2 % ) int matri%
'' Bind the minimum "alue in a ? G ! matri%
int min = mGnArray[][];
for 7int i = ; i @ mGnArray-length; AAi6 '' 7*6
'' Bind min in mGnArray[i], i-e- in the row gi"en by inde% i-
for 7int / = ; / @ mGnArray[i]-length; AA/6 '' 7)6
min = ?ath-min7min, mGnArray[i][/]6;
#ystem-out-println79?inimum "alue, 9 A min6;
1
1
5utput from the program2
?inimum "alue, (
%evie& 'uestions
4.17iven the follo!ing declaration, !hich e&pression returns the size of the array, assuming the
array has been initialized@
int[] array;
Select the one correct ans!er.
a. array[]-length76
b. array-length76
c. array[]-length
d. array-length
e. array[]-size76
f. array-size76
4.2"s it possible to create arrays of length zero@
Select the one correct ans!er.
a. Aes, you can create arrays of any type !ith length zero.
b. Aes, but only for primitive data types.
c. Aes, but only for arrays of ob)ect references.
d. 3o, you cannot create zero$length arrays, but the main76 method may be passed a zero$
length array of #tring references !hen no program arguments are specified.
e. 3o, it is not possible to create arrays of length zero in (ava.
4.3Which one of the follo!ing array declaration statements is not legal@
Select the one correct ans!er.
a. int []a[] = new int [2][2];
b. int a[][] = new int [2][2];
c. int a[][] = new int [][2];
d. int []a[] = new int [2][];
e. int [][]a = new int [2][2];
4.4Which of these array declaration statements are not legal@
Select the t!o correct ans!ers.
a. int[] i[] = 0 0 &, * 1, 0 & 1, 01, 0 &, *, ) 1 1;
b. int i[] = new int[*] 0&, *1;
c. int i[][] = new int[][] 0 0&, *, )1, 02, (, 41 1;
d. int i[][] = 0 0 &, * 1, new int[ * ] 1;
e. int i[2] = 0 &, *, ), 2 1;
4.5What !ould be the result of attempting to compile and run the follo!ing program@
'' Bilename, ?y=lass-/a"a
class ?y=lass 0
public static "oid main7#tring[] args6 0
int size = *;
int[] arr = new int[ size ];
for 7int i = ; i @ size; AAi6 0
#ystem-out-println7arr[i]6;
1
1
1
Select the one correct ans!er.
a. 'he code !ill fail to compile because the array type int[] is incorrect.
b. 'he program !ill compile, but !ill thro! an ArrayInde%.ut.f<ounds$%ception !hen run.
c. 'he program !ill compile and run !ithout error, but !ill produce no output.
d. 'he program !ill compile and run !ithout error and !ill print the numbers , through -<.
e. 'he program !ill compile and run !ithout error and !ill print t!enty times.
f. 'he program !ill compile and run !ithout error and !ill print null t!enty times.
4.67iven the follo!ing program, !hich statement is true@
class ?y=lass 0
public static "oid main7#tring[] args6 0
#tring[] numbers = 0 9one9, 9two9, 9three9, 9four9 1;
if 7args-length == 6 0
#ystem-out-println79no arguments96;
1 else 0
#ystem-out-println7numbers[ args-length ] A 9 arguments96;
1
1
1
Select the one correct ans!er.
a. 'he program !ill fail to compile.
b. 'he program !ill thro! a !ullPointer$%ception !hen run !ith zero program
arguments.
c. 'he program !ill print 9no arguments9 and 9two arguments9 !hen called !ith zero and
three program arguments, respectively.
d. 'he program !ill print 9no arguments9 and 9three arguments9 !hen called !ith zero
and three program arguments, respectively.
e. 'he program !ill print 9no arguments9 and 9four arguments9 !hen called !ith zero and
three program arguments, respectively.
f. 'he program !ill print 9one arguments9 and 9four arguments9 !hen called !ith zero
and three program arguments, respectively.
4.7What !ould be the result of trying to compile and run the follo!ing program@
public class +efaultDalues8est 0
int[] ia = new int[&];
boolean b;
int i;
.b/ect o;
public static "oid main7#tring[] args6 0
+efaultDalues8est instance = new +efaultDalues8est76;
instance-print76;
1
public "oid print76 0
#ystem-out-println7ia[] A 9 9 A b A 9 9 A i A 9 9 A o6;
1
1
Select the one correct ans!er.
a. 'he program !ill fail to compile because of uninitialized variables.
b. 'he program !ill thro! a /a"a-lang-!ullPointer$%ception !hen run.
c. 'he program !ill print B false !a! nullB.
d. 'he program !ill print B false nullB.
e. 'he program !ill print Bnull nullB.
f. 'he program !ill print Bnull false nullB.
4.( De)ining Classes
% class declaration introduces a ne! reference type. "t has the follo!ing general synta&2
<class modifiers class <class name
<extends clause <implements clause '' =lass header
0 '' =lass body
<field declarations
<method declarations
<nested class declarations
<nested interface declarations
<constructor declarations
<initiali!er "loc#s
1
"n the class header, the name of the class is preceded by the key!ord class. "n addition, the class
header can specify the follo!ing information2
scope or accessi"ility modifier (see Section 6.=, p. -/-)
additional class modifiers (see Section 6.;, p. -/6)
any class it extends (see Section 1.-, p. 001)
any interfaces it implements (see Section 1.6, p. 0:-)
'he class body can contain mem"er declarations !hich comprise
field declarations (see Section 0./, p. /-)
method declarations (see Section 6./, p. --0)
nested class and interface declarations (see Section =.-, p. 0;6)
?embers declared static belong to the class and are called static mem"ers, and non$static
members belong to the ob)ects of the class and are called instance mem"ers. "n addition, the
follo!ing can be declared in a class body2
constructor declarations (see Section 6.6, p. --=)
static and instance initiali!er "loc#s (see Section ;.0, p. //-)
'he member declarations, constructor declarations and initializer blocks can appear in any order in
the class body.
"n order to understand !hat code is legal to declare in a class, !e distinguish bet!een static
context and non-static context. % static conte&t is defined by static methods, static field initializers,
and static initializer blocks. % non$static conte&t is defined by instance methods, constructors, non$
static field initializers, and instance initializer blocks. Cy static code !e mean e&pressions and
statements in a static conte&t, and similarly by non-static code !e mean e&pressions and
statements in a non$static conte&t. 5ne crucial difference bet!een the t!o conte&ts is that static
code cannot refer to non$static members.
4.* De)ining $ethods
'he general synta& of a method declaration is
<method modifiers <return type <method name 7<formal parameter list6
<thro$s clause '' ?ethod prototype
0 '' ?ethod body
<local varia"le declarations
<nested local class declarations
<statements
1
"n addition to the name of the method, the method prototype can specify the follo!ing information2
scope or accessi"ility modifier (see Section 6.:, p. -0-)
additional method modifiers (see Section 6.-,, p. -66)
the type of the return value, or "oid if the method does not return any value (see Section
:.6, p. -=1)
a formal parameter list
chec#ed exceptions thro!n by the method in a throws clause (see Section :.<, p. 0,-)
'he formal parameter list is a comma$separated list of parameters for passing information to the
method !hen the method is invoked by a method call (see Section /.-=, p. ;1). %n empty
parameter list must be specified by 7 6. +ach parameter is a simple variable declaration consisting
of its type and name2
<parameter modifier <type <parameter name
'he parameter names are local to the method (see Section 6.:, p. -0/). 'he parameter modifier
final is discussed in Section /.00 on page <6.
'he signature of a method comprises the method name and the formal parameter list only.
'he method body is a "loc# containing the local declarations and the statements of the method.
%ocal varia"le declarations are discussed in Section 0./ on page /-, and nested local class
declarations in Section =.6 on page /,0.
Dike member variables, member methods can be characterized as2
instance methods, !hich are discussed later in this chapter
static methods, (see Section 6.-,, p. -66) !hich are discussed later in this chapter
Statements
Statements in (ava can be grouped into various categories. Eariable declarations !ith e&plicit
initialization of the variables are called declaration statements (see Section 0./, p. /-, and Section
6.-, p. -,0). 5ther basic forms of statements are control flo$ statements (see Section :.-, p. -:;)
and expression statements.
%n expression statement is an e&pression terminated by a semicolon. 'he e&pression is evaluated
for its side effect and its value discarded. 5nly certain types of e&pressions have meaning as
statements. 'hey include the follo!ing2
assignments (see Section /.6, p. 6=)
increment and decrement operators (see Section /.=, p. 1/)
method calls (see Section /.-=, p. ;1)
ob)ect creation e&pression !ith the new operator (see Section /.-1, p. ;6)
% solitary semicolon denotes the empty statement that does nothing.
% block, 01, is a compound statement !hich can be used to group zero or more local declarations
and statements (see Section 6.:, p. -0/). Clocks can be nested, since a block is a statement that
can contain other statements. % block can be used in any conte&t !here a simple statement is
permitted. 'he compound statement !hich is embodied in a block, begins at the left brace, 0, and
ends !ith a matching right brace, 1. Such a block must not be confused !ith an array initialization
block in declaration statements (see Section 6.-, p. -,0).
Dabeled statements are discussed in Section :.6 on page -=-.
!nstance $ethods and Object %e)erence this
"nstance methods belong to every ob)ect of the class and can only be invoked on ob)ects. %ll
members defined in the class, both static and non$static, are accessible in the conte&t of an
instance method. 'he reason is that all instance methods are passed an implicit reference to the
current o"&ect, that is, the ob)ect on !hich the method is being invoked. 'he current ob)ect can be
referenced in the body of the instance method by the key!ord this. "n the body of the method,
the this reference can be used like any other ob)ect reference to access members of the ob)ect. "n
fact, the key!ord this can be used in any non$static conte&t. 'he this reference can be used as a
normal reference to reference the current ob)ect, but the reference cannot be modified.
'he this reference to the current ob)ect is useful in situations !here a local variable hides, or
shado$s, a field !ith the same name. "n +&le 6.6, the t!o parameters no.fKatts and
indicator in the constructor of the Light class have the same names as the fields in the class.
'he e&le also declares a local variable location, !hich has the same name as one of the
fields. 'he reference this can be used to distinguish the fields from the local variables. %t (-), the
this reference is used to identify the field no.fKatts, !hich is assigned the value of the parameter
no.fKatts. Without the this reference at (0), the value of the parameter indicator is assigned
back to this parameter and not to the field by the same name, resulting in a logical error. Similarly
at (/), !ithout the this reference it is the local variable location that is assigned the value of the
parameter site, and not the field by the same name.
Example 4.4 Using this eferen!e
class Light 0
'' Bields
int no.fKatts; '' wattage
boolean indicator; '' on or off
#tring location; '' placement
'' =onstructor
public Light7int no.fKatts, boolean indicator, #tring site6 0
#tring location;
this-no.fKatts = no.fKatts; '' 7&6 Assignment to field-
indicator = indicator; '' 7*6 Assignment to parameter-
location = site; '' 7)6 Assignment to local "ariable-
this-superfluous76; '' 726
superfluous76; '' eFui"alent to call at 726
1
public "oid superfluous76 0 #ystem-out-println7this6; 1 '' 7(6
public static "oid main7#tring[] args6 0
Light light = new Light7&, true, 9loft96;
#ystem-out-println79!o- of watts, 9 A light-no.fKatts6;
#ystem-out-println79Indicator, 9 A light-indicator6;
#ystem-out-println79Location, 9 A light-location6;
1
1
5utput from the program2
LightMdf4ccd
LightMdf4ccd
!o- of watts, &
Indicator, false
Location, null
"f a member is not shado!ed by a local declarations, then the simple name member is considered a
short$hand notation for this-member. "n particular, the this reference can be used e&plicitly to
invoke other methods in the class. 'his is illustrated at (6) in +&le 6.6, !here the method
superfluous76 is called.
"f, for some reason, a method needs to pass the current ob)ect to another method, it can do so
using the this reference. 'his is illustrated at (:) in +&le 6.6, !here the current ob)ect is
passed to the println76 method.
3ote that the this reference cannot be used in a static conte&t, as static code is not e&ecuted in
the conte&t of any ob)ect.
$ethod Overloading
+ach method has a signature, !hich comprises the name of the method and the types and order of
the parameters in the formal parameter list. Several method implementations may have the same
name, as long as the method signatures differ. 'his is called method overloading. Since overloaded
methods have the same name, their parameter lists must be different.
*ather than inventing ne! method names, method overloading can be used !hen the same logical
operation requires multiple implementations. 'he (ava 0 SDF %."s make heavy use of method
overloading. or e&le, the class /a"a-lang-?ath contains an overloaded method min76, !hich
returns the minimum of t!o numeric values.
public static double min7double a, double b6
public static float min7float a, float b6
public static int min7int a, int b6
public static long min7long a, long b6
"n the follo!ing e&les, five implementations of the method methodA are sho!n2
"oid methodA7int a, double b6 0 'C --- C' 1 '' 7&6
int methodA7int a6 0 return a; 1 '' 7*6
int methodA76 0 return &; 1 '' 7)6
long methodA7double a, int b6 0 return b; 1 '' 726
long methodA7int %, double y6 0 return %; 1 '' 7(6 !ot .N-
'he corresponding signatures of the five methods are as follo!s2
methodA7int, double6
-G
methodA7int6
0G2 3umber of parameters.
methodA76
/G2 3umber of parameters.
methodA7double, int6
6G2 5rder of parameters.
methodA7int, double6
:G2 Same as -G.
'he first four implementations of the method named methodA are overloaded correctly, each time
!ith a different parameter list and, therefore, different signatures. 'he declaration at (:) has the
same signature methodA7int, double6 as the declaration at (-) and is, therefore, not a valid
overloading of this method.
"oid bake7=ake k6 0 'C --- C' 1 '' 7&6
"oid bake7Pizza p6 0 'C --- C' 1 '' 7*6
int halfIt7int a6 0 return a'*; 1 '' 7)6
double halfIt7int a6 0 return a'*-; 1 '' 726 !ot .N- #ame signature-
'he method named bake is correctly overloaded at (-) and (0), !ith t!o different signatures. "n
the implementation, changing )ust the return type (as sho!n at (/) and (6)), is not enough to
overload a method, and !ill be flagged as a compile$time error. 'he parameter list in the definitions
must be different. 5verloaded methods should be considered as individual methods that )ust
happen to have the same name. ?ethods !ith the same name are allo!ed since methods are
identified by their signature. %t compile time, the right implementation is chosen based on the
signature of the method call. Details of method overloading resolution can be found in Section 1.0
on page 0/=. 5nly methods declared in the same class and those that are inherited by the class
can be overloaded. ?ethod overloading should not be confused !ith method overriding (see
Section 1.0, p. 0//).
4.4 Constructors
'he main purpose of constructors is to set the initial state of an ob)ect !hen the ob)ect is created
by using the new operator.
% constructor has the follo!ing general synta&2
<accessi"ility modifier <class name 7<formal parameter list6
<thro$s clause '' =onstructor header
0 '' =onstructor body
<local varia"le declarations
<nested local class declarations
<statements
1
Honstructor declarations are very much like method declarations. 8o!ever, the follo!ing
restrictions on constructors should be noted2
?odifiers other than an accessibility modifier are not permitted in the constructor header.
%ccessibility modifiers for constructors are discussed in Section 6.= on page -/-.
Honstructors cannot return a value and, hence, cannot specify a return type, not even "oid,
in the constructor header, but they can contain the simple form of the return statement in
the constructor body.
Honstructor name must be the same as the class name.
Hlass names and method names e&ist in different namespaces. 'hus, there are no name conflicts in
+&le 6.:, !here a method declared at (0) has the same name as the constructor declared at
(-). 8o!ever, using such naming schemes is strongly discouraged.
Example 4.5 "amespa!es
public class !ame 0
!ame76 0 '' 7&6
#ystem-out-println79=onstructor96;
1
"oid !ame76 0 '' 7*6
#ystem-out-println79?ethod96;
1
public static "oid main7#tring[] args6 0
new !ame76-!ame76; '' 7)6 =onstructor call followed by method call-
1
1
5utput from the program2
=onstructor
?ethod
De)ault Constructor
% default constructor is a constructor !ithout any parameters. "n other !ords, it has the follo!ing
signature2
<class name76
"f a class does not specify any constructors, then an implicit default constructor is supplied for the
class. 'he implicit default constructor is equivalent to the follo!ing implementation2
<class name76 0 super76; 1 '' !o parameters- =alls superclass constructor-
'he only action taken by the implicit default constructor is to call the superclass constructor. 'his
ensures that the inherited state of the ob)ect is initialized properly (see Section 1./, p. 06/). "n
addition, all instance variables in the ob)ect are set to the default value of their type.
"n the follo!ing code, the class Light does not specify any constructors.
class Light 0
'' Bields
int no.fKatts; '' wattage
boolean indicator; '' on or off
#tring location; '' placement
'' !o constructors
''---
1
class Hreenhouse 0
'' ---
Light oneLight = new Light76; '' 7&6 =all of implicit default constructor-
1
"n the previous code, the follo!ing implicit default constructor is employed !hen a Light ob)ect is
created at (-)2
Light76 0 super76; 1
Hreating an ob)ect using the new operator !ith the implicit default constructor, as at (-), !ill
initialize the fields of the ob)ect to their default values (i.e., the fields no.fKatts, indicator, and
location in a Light ob)ect !ill be initialized to , false, and null, respectively).
% class can choose to provide an implementation of the default constructor. "n the follo!ing
e&le, the class Light provides an e&plicit default constructor at (-). 3ote that it has the same
name as the class, and that it does not take any parameters.
class Light 0
'' ---
'' $%plicit +efault =onstructor
Light76 0 '' 7&6
no.fKatts = (;
indicator = true;
location = 9G9;
1
''---
1
class Hreenhouse 0
'' ---
Light e%traLight = new Light76; '' 7*6 =all of e%plicit default constructor-
1
'he e&plicit default constructor ensures that any ob)ect created !ith the e&pression new Light76,
as at (0), !ill have its fields no.fKatts, indicator and location initialized to (, true and 9G9,
respectively.
"f a class defines any e&plicit constructors, it can no longer rely on the implicit default constructor
to set the state of the ob)ects. "f such a class requires a default constructor, its implementation
must be provided. "n the e&le belo!, class Light only provides a non$default constructor at
(-). "t is called at (0) !hen an ob)ect of class Light is created !ith the new operator. %ny attempt
to call the default constructor !ill be flagged as a compile time error as sho!n at (/).
class Light 0
'' ---
'' .nly non;default =onstructor
Light7int no.fKatts, boolean indicator, #tring location6 0 '' 7&6
this-no.fKatts = no.fKatts;
this-indicator = indicator;
this-location = location;
1
''---
1
class Hreenhouse 0
'' ---
Light moreLight = new Light7&, true, 9Hreenhouse96; '' 7*6 .N-
'' Light firstLight = new Light76; '' 7)6 =ompile time error-
1
Overloaded Constructors
Dike methods, constructors can also be overloaded. Since the constructors in a class all have the
same name as the class, their signatures are differentiated by their parameter lists. "n the
follo!ing e&le, the class Light no! provides both an e&plicit implementation of the default
constructor at (-) and a non$default constructor at (0). 'he constructors are overloaded, as is
evident by their signatures. 'he non$default constructor is called !hen an ob)ect of class Light is
created at (/), and the default constructor is like!ise called at (6). 5verloading of constructors
allo!s appropriate initialization of ob)ects on creation, depending on the constructor invoked (see
also chaining of constructors in Section 1./, p. 06/.)
class Light 0
'' ---
'' $%plicit +efault =onstructor
Light76 0 '' 7&6
no.fKatts = (;
indicator = true;
location = 9G9;
1
'' !on;default =onstructor
Light7int no.fKatts, boolean indicator, #tring location6 0 '' 7*6
this-no.fKatts = no.fKatts;
this-indicator = indicator;
this-location = location;
1
''---
1
class Hreenhouse 0
'' ---
Light moreLight = new Light7&, true, 9Hreenhouse96; '' 7)6 .N-
Light firstLight = new Light76; '' 726 .N-
1
4.+ Scope %ules
(ava provides e&plicit accessibility modifiers to control the accessibility of members in a class by
e&ternal clients (see Section 6.<, p. -/=), but in t!o areas access is governed by specific scope
rules2
Hlass scope for members2 ho! member declarations are accessed !ithin the class.
Clock scope for local variables2 ho! local variable declarations are accessed !ithin a block.
Class Scope )or $embers
Class scope concerns accessing members (including inherited ones) from code !ithin a class. 'able
6.- gives an overvie! of ho! static and non$static code in a class can access members of the class,
including those that are inherited. 'able 6.- assumes the follo!ing declarations2
class #uper!ame 0
int instanceDarIn#uper;
static int staticDarIn#uper;
"oid instance?ethodIn#uper76 0 'C --- C' 1
static "oid static?ethodIn#uper76 0 'C --- C' 1
'' ---
1
class =lass!ame e%tends #uper!ame 0
int instanceDar;
static int staticDar;
"oid instance?ethod76 0 'C --- C' 1
static "oid static?ethod76 0 'C --- C' 1
'' ---
1
'he golden rule is that static code cannot access non$static members by their simple names. Static
code is not e&ecuted in the conte&t of an ob)ect, therefore the references this and super are not
available. %n ob)ect has kno!ledge of its class, therefore, static members are al!ays accessible in a
non$static conte&t.
3ote that using the class name to access static members !ithin the class is no different from ho!
e&ternal clients access these static members.
Some factors that can influence the scope of a member declaration are
shado!ing of a field declaration, either by local variables (see Section 6./, p. --6) or by
declarations in the subclass (see Section 1.0, p. 0//)
initializers preceding the field declaration (see Section ;.0, p. //-)
overriding an instance method from a superclass (see Section 1.0, p. 0//)
hiding a static method declared in a superclass (see Section 1.0, p. 0//)
%ccessing members !ithin nested classes is discussed in Hhapter =.
#a$le 4.1. A!!essing Mem$ers %it&in a 'lass
Mem$er
de!larations
"on(stati! 'ode in t&e 'lass
ClassName 'an efer to t&e Mem$er
as
)tati! 'ode in t&e 'lass ClassName
'an efer to t&e Mem$er as
"nstance
variables
instanceDar
this-instanceDar
instanceDarIn#uper
this-instanceDarIn#uper
super-instanceDarIn#uper
3ot possible
"nstance
methods
instance?ethod76
this-instance?ethod76
instance?ethodIn#uper76
this-instance?ethodIn#uper76
super-instance?ethodIn#uper76
3ot possible
Static
variables
staticDar
this-staticDar
=lass!ame-staticDar
staticDarIn#uper
this-staticDarIn#uper
super-staticDarIn#uper
=lass!ame-staticDarIn#uper
#uper!ame-staticDarIn#uper
staticDar
=lass!ame-staticDar
staticDarIn#uper
=lass!ame-staticDarIn#uper
#uper!ame-staticDarIn#uper
Static
methods
static?ethod76
this-static?ethod76
=lass!ame-static?ethod76
static?ethodIn#uper76
this-static?ethodIn#uper76
super-static?ethodIn#uper76
=lass!ame-static?ethodIn#uper76
#uper!ame-static?ethodIn#uper76
static?ethod76
=lass!ame-static?ethod76
static?ethodIn#uper76
=lass!ame-static?ethodIn#uper76
#uper!ame-static?ethodIn#uper76
Within a class =, reference variables of type = can be used to access all members in the class =,
regardless of their accessibility modifiers. "n +&le 6.1, the method duplicateLight at (-) in
class Light has a parameter oldLight and a local variable newLight that are references to Light
ob)ects. +ven though the fields of the class are pri"ate, they are accessible through the t!o
references (oldLight and newLight) in the method duplicateLight76 as sho!n at (0), (/), and
(6).
Example 4.6 'lass )!ope
class Light 0
'' Instance "ariables
pri"ate int no.fKatts; '' wattage
pri"ate boolean indicator; '' on or off
pri"ate #tring location; '' placement
'' Instance methods
public "oid switch.n76 0 indicator = true; 1
public "oid switch.ff76 0 indicator = false; 1
public boolean is.n76 0 return indicator; 1
public static Light duplicateLight7Light oldLight6 0 '' 7&6
Light newLight = new Light76;
newLight-no.fKatts = oldLight-no.fKatts; '' 7*6
newLight-indicator = oldLight-indicator; '' 7)6
newLight-location = oldLight-location; '' 726
return newLight;
1
1
,loc- Scope )or .ocal ariables
Declarations and statements can be grouped into a "loc# using braces, 01. Clocks can be nested,
and certain scope rules apply to local variable declarations in such blocks. % local declaration can
appear any!here in a block. 'he general rule is that a variable declared in a block is in scope inside
the block in !hich it is declared, but it is not accessible outside of this block. "t is not possible to
redeclare a variable if a local variable of the same name is already declared in the current scope.
Docal variables of a method are comprised of formal parameters of the method and variables that
are declared in the method body. 'he local variables in a method are distinct for each invocation,
and have their o!n storage.
% method body is a block. .arameters cannot be redeclared in the method body, as sho!n at (-) in
Clock - (see igure 6.0).
Figure 4.2. *lo!+ )!ope
% local variable4already declared in an enclosing block and, therefore, visible in a nested block4
cannot be redeclared in the nested block. 'hese cases are sho!n at (/), (:), and (1).
% local variable in a block can be redeclared in another block if the blocks are dis&oint, that is, they
do not overlap. 'his is the case for variable i at (0) in Clock / and at (6) in Clock 6, as these t!o
blocks are dis)oint.
'he scope of a declaration begins from !here it is declared in the block and ends !here this block
terminates. 'he scope of the loop variable inde% is Clock 0. +ven though Clock 0 is nested in Clock
-, the declaration of the variable inde% at (=) in Clock - is valid. "ts scope spans from its
declaration to the end of this block, and it does not overlap !ith that of the loop variable inde% in
Clock 0.
%evie& 'uestions
4.,Which one of these is a valid method declaration@
Select the one correct ans!er.
a. "oid method& 0 'C --- C' 1
b. "oid method*76 0 'C --- C' 1
c. "oid method)7"oid6 0 'C --- C' 1
d. method276 0 'C --- C' 1
e. method(7"oid6 0 'C --- C' 1
4.-7iven the follo!ing code, !hich statements can be placed at the indicated position !ithout
causing compilation errors@
public class 8hisOsage 0
int planets;
static int suns;
public "oid gaze76 0
int i;
'' --- insert statements here ---
1
1
Select the three correct ans!ers.
a. i = this-planets;
b. i = this-suns;
c. this = new 8hisOsage76;
d. this-i = 2;
e. this-suns = planets;
4.1.7iven the follo!ing pairs of method declarations, !hich statements are true@
"oid fly7int distance6 01
int fly7int time, int speed6 0 return timeCspeed; 1
"oid fall7int time6 01
int fall7int distance6 0 return distance; 1
"oid glide7int time6 01
"oid Hlide7int time6 01
Select the t!o correct ans!ers.
a. 'he first pair of methods !ill compile correctly and overload the method name fly.
b. 'he second pair of methods !ill compile correctly and overload the method name fall.
c. 'he third pair of methods !ill compile correctly and overload the method name glide.
d. 'he second pair of methods !ill not compile correctly.
e. 'he third pair of methods !ill not compile correctly.
4.117iven a class named <ook, !hich one of these is a valid constructor declaration for the class@
Select the one correct ans!er.
a. <ook7<ook b6 01
b. <ook <ook76 01
c. pri"ate final <ook76 01
d. "oid <ook76 01
e. public static "oid <ook7#tring[] args6 01
f. abstract <ook76 01
4.12Which statements are true@
Select the t!o correct ans!ers.
a. %ll classes must define a constructor.
b. % constructor can be declared pri"ate.
c. % constructor can return a value.
d. % constructor must initialize all the fields of a class.
e. % constructor can access the non$static members of a class.
4.13What !ill be the result of attempting to compile the follo!ing program@
public class ?y=lass 0
long "ar;
public "oid ?y=lass7long param6 0 "ar = param; 1 '' 7&6
public static "oid main7#tring[] args6 0
?y=lass a, b;
a = new ?y=lass76; '' 7*6
b = new ?y=lass7(6; '' 7)6
1
1
Select the one correct ans!er.
a. % compilation error !ill occur at (-), since constructors cannot specify a return value.
b. % compilation error !ill occur at (0), since the class does not have a default constructor.
c. % compilation error !ill occur at (/), since the class does not have a constructor !hich
takes one argument of type int.
d. 'he program !ill compile correctly.
4./ 0ac-ages
% package in (ava is an encapsulation mechanism that can be used to group related classes,
interfaces, and subpackages.
igure 6./ sho!s an e&le of a package hierarchy, comprising of a package called wizard that
contains t!o other packages2 pandoras<o% and spells. 'he package pandoras<o% has a class
called =lown that implements an interface called ?agic, also found in the same package. "n
addition, the package pandoras<o% has a class called Lo"ePotion and a subpackage called
artifacts containing a class called Ailment. 'he package spells has t!o classes2 <aldness and
Lo"ePotion. 'he class <aldness is a subclass of class Ailment found in the subpackage artifacts
in the package pandoras<o%.
Figure 4.3. /a!+age 0ierar!&y
'he dot (-) notation is used to uniquely identify package members in the package hierarchy. 'he
class wizard-pandoras<o%-Lo"ePotion is different from the class wizard-spells-Lo"ePotion.
'he Ailment class can be easily identified by the name wizard-pandoras<o%-artifacts-Ailment.
'his is called the fully 'ualified name of the package member. "t is not surprising that most (ava
programming environments map the fully qualified name of packages on the underlying
(hierarchical) file system. or e&le, on a #ni& system, the class file Lo"ePotion-class
corresponding to the class wizard-pandoras<o%-Lo"ePotion !ould be found under the directory
wizard'pandoras<o%.
% global naming scheme has been proposed to use the "nternet domain names to uniquely identify
packages. "f the above package wizard !as implemented by a company called Sorcerers Dimited
that o!ns the domain sorcerersltd-com, its fully qualified name !ould be2
com-sorcerersltd-wizard
'he subpackage wizard-pandoras<o%-artifacts could easily have been placed else!here, as long
as it !as uniquely identified. Subpackages do not affect the accessibility of the members. or all
intent and purposes, subpackages are more an organi!ational feature rather than a language
feature. %ccessibility of members in a package is discussed in Section 6.=. %ccessibility of members
in classes and interfaces is discussed in Section 6.<.
De)ining 0ac-ages
% package hierarchy represents an organization of the (ava classes and interfaces. "t does not
represent the source code organization of the classes and interfaces. 'he source code is of no
consequence in this regard. +ach (ava source file (also called compilation unit) can contain zero or
more definitions of classes and interfaces, but the compiler produces a separate class file
containing the (ava byte code for each of them. % class or interface can indicate that its (ava byte
code be placed in a particular package, using a package declaration.
'he package statement has the follo!ing synta&2
package <fully 'ualified pac#age name;
%t most one package declaration can appear in a source file, and it must be the first statement in
the unit. 'he package name is saved in the (ava byte code for the types contained in the package.
3ote that this scheme has t!o consequences. irst, all the classes and interfaces in a source file
!ill be placed in the same package. Secondly, several source files can be used to specify the
contents of a package.
"f a package declaration is omitted in a compilation unit, the (ava byte code for the declarations in
the compilation unit !ill belong to an unnamed pac#age, !hich is typically synonymous !ith the
current !orking directory on the host system.
+&le 6.= on page -/- illustrates ho! the package wizard-pandoras<o% in igure 6./ can be
defined using the package declaration.
#sing 0ac-ages
'he accessibility of types (classes and interfaces) in a package may deny access from outside the
package. 7iven a reference type that is accessible from outside a package, the reference type can
be accessed in t!o !ays. 'he first form uses the fully qualified name of the type. 8o!ever, !riting
long names can become tedious. 'he second form uses the import declaration to provide a
shorthand notation for specifying the name of the type.
'he import declarations must be the first statement after any package declaration in a source file.
'he simple form of the import declaration has the follo!ing synta&2
import <fully 'ualified type name;
'his is called single type import. %s the name implies, such an import declaration provides a
shorthand notation for a single class or interface. 'he simple name of the type (i.e., its identifier)
can be used to access this particular type. 7iven the follo!ing import declaration2
import wizard-pandoras<o%-=lown;
the name =lown can be used in the source file to refer to this class.
%lternatively, the follo!ing form of the import declaration can be used2
import <fully 'ualified pac#age name-C;
'his is called type import on demand. "t allo!s any type from the specified package to be accessed
by its simple name.
%n import declaration does not recursively import subpackages. 'he declaration does not result in
inclusion of the source code of the types. 'he declaration only imports type names (i.e., it makes
type names available to the code in a compilation unit).
%ll compilation units implicitly import the /a"a-lang package (see Section -,.-, p. /;;). 'his is the
reason !hy !e can refer to the class #tring by its simple name, and not need to use its fully
qualified name /a"a-lang-#tring all the time.
+&le 6.= sho!s several usages of the import declaration. 8ere !e !ill dra! attention to the
class <aldness in the file <aldness-/a"a. 'his class relies on t!o classes that have the same
simple name Lo"ePotion but are in different packages2 wizard-pandoras<o% and wizard-spells,
respectively. 'o distinguish bet!een the t!o classes, !e can use their fully qualified names.
8o!ever, since one of them is in the same package as the class <aldness, it is enough to fully
qualify the class from the other package. 'his solution is used in the follo!ing code. Such name
conflicts can usually be resolved by using variations of the import declaration together !ith fully
qualified names.
'' Bile, <aldness-/a"a
package wizard-spells; '' 7&6Package declaration
---
import wizard-pandoras<o%-artifacts-C; '' 7)6 Import from subpackage
---
public class <aldness e%tends Ailment 0 '' 726 Abbre"iated name for Ailment
wizard-pandoras<o%-Lo"ePotion tlc.ne; '' 7(6 Bully Fualified name
Lo"ePotion tlc8wo; '' 746 =lass in same package
---
1
1
---
'he class <aldness e&tends the class Ailment, !hich is in the subpackage artifacts of the
wizard-pandoras<o% package. % ne! import declaration at (/) is used to import the types from
the subpackage artifacts.
'he follo!ing e&le sho!s ho! single type import can be used to disambiguate a class name
!hen access to the class is ambiguous by simple name. 'he follo!ing import declaration allo!s the
simple name List as shorthand for the /a"a-awt-List class as e&pected2
import /a"a-awt-C; '' imports all class names from /a"a-awt
7iven the follo!ing t!o import declarations2
import /a"a-awt-C; '' imports all class names from /a"a-awt
import /a"a-util-C; '' imports all class names from /a"a-util
the simple name List is no! ambiguous as both the classes /a"a-util-List and /a"a-awt-List
match.
%dding a single type import for the /a"a-awt-List class e&plicitly allo!s the simple name List as
a shorthand notation for this class2
import /a"a-awt-C; '' imports all class names from /a"a-awt
import /a"a-util-C; '' imports all class names from /a"a-util
import /a"a-awt-List; '' imports the class name List from /a"a-awt
Compiling and %unning Code )rom 0ac-ages
%s mentioned earlier, a package hierarchy can be mapped on a hierarchical file system. We can
think of a package name as a path in the file system. *eferring to +&le 6.=, the package name
wizard-pandoras<o% corresponds to the path name wizard'pandoras<o%. 'he /a"ac compiler can
place the byte code in a directory that corresponds to the package declaration of the compilation
unit. 'he (ava byte code for all the classes (and interfaces) specified in the source files =lown-/a"a
and Lo"ePotion-/a"a !ill be placed in the directory named wizard'pandoras<o%, as these source
files have the follo!ing package declaration2
package wizard-pandoras<o%;
'he absolute path of the wizard'pandoras<o% directory is specified by using the ;d option (d for
destination) !hen compiling !ith the /a"ac compiler. %ssuming that the current directory is called
'pg/c'work, and all the source code files are to be found here, the command
P/a"ac ;d - =lown-/a"a Ailment-/a"a <aldness-/a"a
issued in the work directory, !ill create -'wizard'pandoras<o% (and any other subdirectories
required) under the current directory, and place the (ava byte code for all the classes (and
interfaces) in the directories corresponding to the package names. 'he dot (-) after the ;d option
denotes the current directory. %fter compiling the code in +&le 6.= using the /a"ac command
above, the file hierarchy under the 'pg/c'work directory should mirror the package hierarchy in
igure 6./. Without the ;d option, the default behavior of the /a"ac compiler is to place all class
files directly under the current directory, rather than in the appropriate subdirectories.
(o$ do $e run the program@ Since the current directory is 'pg/c'work and !e !ant to run
=lown-class, the fully qualified name of the =lown class must be specified in the /a"a command
P/a"a wizard-pandoras<o%-=lown
'his !ill load the class =lown from the byte code in the file -'wizard'pandoras<o%'=lown-class,
and start the e&ecution of its main76 method.
'he tools documentation for the (ava 0 SDF e&plains ho! to organize packages in more elaborate
schemes. "n particular, the =LA##PA8> environment variable can be used to specify multiple
locations !here (ava tools should search !hen loading classes and resources.
#&e 1A Utility
'he (%* ((ava %*chive) utility provides a convenient !ay of bundling and deploying (ava programs.
% (%* file is created by using the /ar tool. % typical (%* file for an application !ill contain the class
files and any other resources needed by the application (for e&le image and audio files). "n
addition, a special manifest file is also created and included in the archive. 'he manifest file
contains pertinent information, such as !hich class contains the main76 method for starting the
application.
'he /ar command has many options (akin to the #ni& tar command). % typical command for
making a (%* file for an application (for e&le, +&le 6.=) has the follo!ing synta&2
P/ar cmf whereismain-t%t bundledApp-/ar wizard
5ption c tells the /ar tool to create an archive. 5ption m is used to create and include a manifest
file. "nformation to be included in the manifest file comes from a te&t file specified on the command
line (whereismain-t%t). 5ption f specifies the name of the archive to be created
(bundledApp-/ar). 'he (%* file name can be any valid file name. iles to be included in the archive
are listed on the command line after the (%* file name. "n the command line above, the contents
under the wizard directory !ill be archived. "f the order of the options m and f is s!itched in the
command line, the order of the respective file names for these options must also be s!itched.
"nformation to be included in the manifest file is specified as name$value pairs. "n +&le 6.=,
program e&ecution should start in the main76 method of the wizard-pandoras<o%-=lown class.
'he file whereismain-t%t has the follo!ing single te&t line2
?ain;=lass, wizard-pandoras<o%-=lown
'he value of the predefined header named ?ain;=lass specifies the e&ecution entry point of the
application. 'he last te&t line in the file must be terminated by a ne!line as !ell, in order to be
processed by the /ar tool. 'his is also true even if the file only has a single line.
'he application in an archive can be run by issuing the follo!ing command2
P/a"a ;/ar bundledApp-/ar
.rogram arguments can be specified after the (%* file name.
4.1 Accessibility $odi)iers )or 2op3level Classes and
!nter)aces
'op$level classes and interfaces !ithin a package can be declared as public. 'his means that they
are accessible from every!here, both inside and outside of their package. "f the accessibility
modifier is omitted, then they are only accessible in the package and not in any other packages or
subpackages. 'his is called pac#age or default accessi"ility.
%ccessibility modifiers for nested classes and interfaces are discussed in Section =.- on page 0;6.
Example 4.7 A!!essi$ility Modifiers for 'lasses and 2nterfa!es
'' Bile, =lown-/a"a
package wizard-pandoras<o%; '' 7&6 Package declaration
import wizard-pandoras<o%-artifacts-Ailment; '' 7*6 Importing class
public class =lown implements ?agic 0
Lo"ePotion tlc; '' 7)6 =lass in same package
wizard-pandoras<o%-artifacts-Ailment problem;'' 726 Bully Fualified class name
=lown76 0
tlc = new Lo"ePotion79passion96;
problem = new Ailment79flu96; '' 7(6 Abbre"iated class name
1
public "oid le"itate76 0 #ystem-out-println79Le"itating96; 1
public "oid mi%Potion76 0 #ystem-out-println79?i%ing 9 A tlc6; 1
public "oid healAilment76 0 #ystem-out-println79>ealing 9 A problem6; 1
public static "oid main7#tring[] args6 0 '' 746
=lown /oker = new =lown76;
/oker-le"itate76;
/oker-mi%Potion76;
/oker-healAilment76;
1
1
interface ?agic 0 "oid le"itate76; 1 '' 756
QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ
'' Bile, Lo"ePotion-/a"a
package wizard-pandoras<o%; '' 7&6 Package declaration
public class Lo"ePotion 0 '' 7*6 Accessible outside package
#tring potion!ame;
public Lo"ePotion7#tring name6 0 potion!ame = name; 1
public #tring to#tring76 0 return potion!ame; 1
1
QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ
'' Bile, Ailment-/a"a
package wizard-pandoras<o%-artifacts; '' 7&6 Package declaration
public class Ailment 0 '' 7*6 Accessible outside package
#tring ailment!ame;
public Ailment7#tring name6 0 ailment!ame = name; 1
public #tring to#tring76 0 return ailment!ame; 1
1
QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ
'' Bile, <aldness-/a"a
package wizard-spells; '' 7&6Package declaration
import wizard-pandoras<o%-C; '' 7*6 Import of classes'interface
import wizard-pandoras<o%-artifacts-C; '' 7)6 Import from subpackage
public class <aldness e%tends Ailment 0 '' 726 Abbre"iated name for Ailment
wizard-pandoras<o%-Lo"ePotion tlc.ne; '' 7(6 Bully Fualified name
Lo"ePotion tlc8wo; '' 746 =lass in same package
<aldness7#tring name6 0
super7name6;
tlc.ne = new wizard-pandoras<o%- '' 756 Bully Fualified name
Lo"ePotion79romance96;
tlc8wo = new Lo"ePotion76; '' 7E6 =lass in same package
1
1
class Lo"ePotion '' implements ?agic '' 736 !ot accessible
0 public "oid le"itate7601 1
Hompiling and running the program from the current !orking directory results in the follo!ing2
P/a"ac ;d - =lown-/a"a Ailment-/a"a <aldness-/a"a
P/a"a wizard-pandoras<o%-=lown
Le"itating
?i%ing passion
>ealing flu
"n +&le 6.=, the class =lown and the interface ?agic are placed in a package called
wizard-pandoras<o%. 'he public class =lown is accessible from every!here. 'he ?agic interface
has default accessibility, and can only be accessed !ithin the package wizard-pandoras<o%. "t is
not accessible from other packages, not even in any packages nested in this package.
'he class Lo"ePotion is also placed in the package called wizard-pandoras<o%. 'he class has
public accessibility and is, therefore, accessible from other packages. 'he t!o files =lown-/a"a
and Lo"ePotion-/a"a demonstrate ho! several compilation units can be used to group classes in
the same package.
'he class =lown, from the file =lown-/a"a, uses the class Ailment. 'he e&le sho!s t!o !ays in
!hich a class can access classes from other packages2
-. Denote the class by its fully qualified class name, as sho!n at (6)
(wizard-pandoras<o%-artifacts-Ailment6.
0. "mport the class e&plicitly from the package wizard-pandoras<o%-artifacts as sho!n at
(0) and use the simple class name Ailment as sho!n at (:).
"n the file <aldness-/a"a at (<), the class Lo"ePotion !ishes to implement the interface ?agic
from the package wizard-pandoras<o%, but cannot do so, although the file imports from this
package. 'he reason is that the interface ?agic has default accessibility and can, therefore, only be
accessed !ithin the package wizard-pandoras<o%.
(ust because the class is accessible, it does not necessarily mean that members of the class are
also accessible. ?ember accessibility is governed separately from class accessibility, as e&plained in
Section 6.:.
#a$le 4.2. )ummary of A!!essi$ility Modifiers for 'lasses and 2nterfa!es
Modifiers #op(le3el 'lasses and 2nterfa!es
default (no modifier) %ccessible in its package (package accessibility)
public
%ccessible any!here
4.4 Other $odi)iers )or Classes
?odifiers abstract and final can be applied to top$level and nested classes.
abstract Classes
% class can be specified !ith the key!ord abstract to indicate that it cannot be instantiated. %
class might choose to do this if the abstraction it represents is so general that it needs to be
specialized in order to be of practical use. % class Dehicle might be specified as abstract to
represent the general abstraction of a vehicle, as creating instances of the class !ould not make
much sense. Hreating instances of non$abstract subclasses, like =ar and <us, !ould make more
sense, as this !ould make the abstraction more concrete.
% class that has one or more abstract methods (see Section 6.-,, p. -6=) must be declared
abstract. 5bviously such classes cannot be instantiated, as their implementation is only partial. %
class might choose this strategy to dictate certain behavior, but allo! its subclasses the freedom to
provide the relevant implementation. "n other !ords, subclasses of the abstract class have to take
a stand and provide implementations of inherited abstract methods before they can be
instantiated. % subclass that does not provide an implementation of its inherited abstract methods
must also be declared abstract.
"n +&le 6.;, the definition of abstract class Light has an abstract method kwhPrice at (-).
'his forces its subclasses to provide the implementation for this method. 'he subclass 8ubeLight
provides an implementation for the method kwhPrice at (0). 'he class Bactory creates an instance
of class 8ubeLight at (/). *eference variables of an abstract class can be declared, as sho!n at
(6), but an abstract class cannot be instantiated, as sho!n at (:). *eferences of an abstract
class can denote ob)ects of the subclasses, as sho!n at (1).
Example 4., A$stra!t 'lasses
abstract class Light 0
'' Bields
int no.fKatts; '' wattage
boolean indicator; '' on or off
#tring location; '' placement
'' Instance methods
public "oid switch.n76 0 indicator = true; 1
public "oid switch.ff76 0 indicator = false; 1
public boolean is.n76 0 return indicator; 1
'' Abstract Instance ?ethod
abstract public double kwhPrice76; '' 7&6 !o method body
1
class 8ubeLight e%tends Light 0
'' Bields
int tubeLength;
'' Implementation of inherited abstract method-
public double kwhPrice76 0 return *-5(; 1 '' 7*6
1
public class Bactory 0
public static "oid main7#tring[] args6 0
8ubeLight cellarLight = new 8ubeLight76; '' 7)6 .N
Light nightLight; '' 726 .N
'' Light tableLight = new Light76; '' 7(6 =ompile time error
nightLight = cellarLight; '' 746 .N
#ystem-out-println79NK> price, 9 A nightLight-kwhPrice766;
1
1
5utput from the program2
NK> price, *-5(
"nterfaces )ust specify the method prototypes and not any implementation9 they are, by their
nature, implicitly abstract (i.e., they cannot be instantiated). 'hough it is legal, it is redundant to
declare an interface !ith the key!ord abstract.
final Classes
% class can be declared final to indicate that it cannot be e&tended9 that is, one cannot declare
subclasses of a final class. 'his implies that one cannot override any methods declared in such a
class. "n other !ords, the class behavior cannot be changed by subclassing. 'he class marks the
lo!er boundary of its implementation inheritance hierarchy. 5nly a class !hose definition is
complete (i.e., has implementations of all its methods) can be declared final.
% final class must be complete, !hereas an abstract class is considered incomplete. Hlasses,
therefore, cannot be both final and abstract at the same time. "nterfaces, !hich are inherently
abstract, thus cannot be declared final. % final class and an interface represent t!o e&tremes
!hen it comes to providing implementation. %n abstract class represents a compromise bet!een
these t!o e&tremes.
'he (ava %." includes many final classes9 for e&le, /a"a-lang-#tring !hich cannot be
specialized any further by subclassing.
"f it is decided that the class 8ubeLight in +&le 6.; cannot, or should not, be e&tended, it can
be declared final2
final class 8ubeLight e%tends Light 0
'' Bields
int tubeLength;
'' Implementation of inherited abstract method-
public double kwhPrice76 0 return *-5(; 1
1
Discussion of final methods, fields and local variables can be found in Section 6.-,, p. -61.
#a$le 4.3. )ummary of 4t&er Modifiers for 'lasses and 2nterfa!es
Modifiers 'lasses 2nterfa!es
abstract
Hlass may contain abstract methods and thus, cannot be instantiated. "mplied.
final
'he class cannot be e&tended (i.e., it cannot be subclassed). 3ot possible.
%evie& 'uestions
4.147iven the follo!ing class, !hich of these are valid !ays of referring to the class from outside of
the package net-basemaster@
package net-basemaster;
public class <ase 0
'' ---
1
Select the t!o correct ans!ers.
a. Cy simply referring to the class as <ase.
b. Cy simply referring to the class as basemaster-<ase.
c. Cy simply referring to the class as net-basemaster-<ase.
d. Cy importing !ith net-basemaster-C and referring to the class as <ase.
e. Cy importing !ith net-C and referring to the class as basemaster-<ase.
4.15Which one of the follo!ing class definitions is a valid definition of a class that cannot be
instantiated@
Select the one correct ans!er.
a-
b- class Hhost 0
c- abstract "oid haunt76;
d- 1
e.
f-
g- abstract class Hhost 0
h- "oid haunt76;
i- 1
5.
k-
l- abstract class Hhost 0
m- "oid haunt76 01;
n- 1
o.
p-
F- abstract Hhost 0
r- abstract "oid haunt76;
s- 1
t.
u-
"- static class Hhost 0
w- abstract haunt76;
%- 1
y.
4.16Which one of the follo!ing class definitions is a valid definition of a class that cannot be
e&tended@
Select the one correct ans!er.
a. class Link 0 1
b. abstract class Link 0 1
c. nati"e class Link 0 1
d. static class Link 0 1
e. final class Link 0 1
f. pri"ate class Link 0 1
g. abstract final class Link 0 1
4.5 $ember Accessibility $odi)iers
Cy specifying member accessibility modifiers, a class can control !hat information is accessible to
clients (i.e., other classes). 'hese modifiers help a class to define a contract so that clients kno!
e&actly !hat services are offered by the class.
%ccessibility of members can be one of the follo!ing2
public
protected
default (also called pac#age accessi"ility)
pri"ate
% member has package or default accessibility !hen no accessibility modifier is specified.
"n the follo!ing discussion on accessibility modifiers for members of a class, keep in mind that the
member accessibility modifier only has meaning if the class (or one of its subclasses) is accessible
to the client. %lso, note that only one accessibility modifier can be specified for a member. 'he
discussion in this section applies to both instance and static members of top$level classes.
Discussion of member accessibility for nested classes is deferred to Hhapter =.
"n #?D notation the prefi&es A , R, and ;, !hen applied to a member name, indicate public,
protected, and pri"ate member accessibility, respectively. 3o prefi& indicates default or package
accessibility.
public $embers
.ublic accessibility is the least restrictive of all the accessibility modifiers. % public member is
accessible from any!here, both in the package containing its class and in other packages !here
this class is visible. 'his is true for both instance and static members.
+&le 6.< contains t!o source files, sho!n at (-) and (1). 'he package hierarchy defined by the
source files is depicted in igure 6.6, sho!ing the t!o packages packageA and package< containing
their respective classes. Hlasses in package package< use classes from package packageA.
#uperclassA in packageA has t!o subclasses2 #ubclassA in packageA and #ubclass< in package<.
Example 4.- /u$li! A!!essi$ility of Mem$ers
'' Bilename, #uperclassA-/a"a 7&6
package packageA;
public class #uperclassA 0
public int superclassDarA; '' 7*6
public "oid superclass?ethodA76 0'C---C'1 '' 7)6
1
class #ubclassA e%tends #uperclassA 0
"oid subclass?ethodA76 0 superclassDarA = &; 1 '' 726 .N-
1
class Any=lassA 0
#uperclassA ob/ = new #uperclassA76;
"oid any=lass?ethodA76 0
ob/-superclass?ethodA76; '' 7(6 .N-
1
1
QQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQQ
'' Bilename, #ubclass<-/a"a 746
package package<;
import packageA-C;
public class #ubclass< e%tends #uperclassA 0
"oid subclass?ethod<76 0 superclass?ethodA76; 1 '' 756 .N-
1
class Any=lass< 0
#uperclassA ob/ = new #uperclassA76;
"oid any=lass?ethod<76 0
ob/-superclassDarA = *; '' 7E6 .N-
1
1
Figure 4.4. /u$li! A!!essi$ility
%ccessibility is illustrated in +&le 6.< by the accessibility modifiers for the field superclassDarA
and the method superclass?ethodA at (0) and (/), respectively, defined in class #uperclassA.
'hese members are accessed from four different clients in +&le 6.<.
Hlient -2 rom a subclass in the same package, !hich accesses an inherited field.
#ubclassA at (6) is such a client.
Hlient 02 rom a non$subclass in the same package, !hich invokes a method on an instance
of the class. Any=lassA at (:) is such a client.
Hlient /2 rom a subclass in another package, !hich invokes an inherited method.
#ubclass< at (=) is such a client.
Hlient 62 rom a non$subclass in another package, !hich accesses a field in an instance of
the class. Any=lass< at (;) is such a client.
"n +&le 6.<, the field superclassDarA and the method superclass ?ethodA have public
accessibility, and are accessible by all the four clients listed above. Subclasses can access their
inherited public members by their simple name, and all clients can access public members through
an instance of the class. .ublic accessibility is depicted in igure 6.6.
protected $embers
% protected member is accessible in all classes in the package containing its class, and by all
subclasses of its class in any package !here this class is visible. "n other !ords, non$subclasses in
other packages cannot access protected members from other packages. "t is less restrictive than
the default accessibility.
"n +&le 6.<, if the field superclassDarA and the method superclass ?ethodA have protected
accessibility, then they are accessible !ithin package packageA, and only accessible by subclasses
in any other packages.
public class #uperclassA 0
protected int superclassDarA; '' 7*6
protected "oid superclass?ethodA76 0'C---C'1 '' 7)6
1
Hlient 6 in package package< cannot access these members, as sho!n in igure 6.:.
Figure 4.5. /rote!ted A!!essi$ility
% subclass in another package can only access protected members in the superclass via references
of its o!n type or its subtypes. 'he follo!ing ne! definition of #ubclass< in package< from
+&le 6.< illustrates the point2
'' Bilename, #ubclass<-/a"a
package package<;
import packageA-C;
public class #ubclass< e%tends #uperclassA 0 '' In package<-
#ubclass< ob/Ief< = new #ubclass<76; '' 7&6
"oid subclass?ethod<7#uperclassA ob/IefA6 0
ob/Ief<-superclass?ethodA76; '' 7*6 .N-
ob/Ief<-superclassDarA = (; '' 7)6 .N-
ob/IefA-superclass?ethodA76; '' 726 !ot .N-
ob/IefA-superclassDarA = &; '' 7(6 !ot .N-
1
1
'he class #ubclass< defines a field of type #ubclass< (ob/Ief<). 'he method subclass?ethod<76
has a formal parameter ob/IefA of type #uperclassA. %ccess is permitted to a protected member
of the #uperclassA in packageA by a reference of the subclass, as sho!n at (0) and (/), but not
by a reference of its superclass, as sho!n at (6) and (:). *eferences to the field superclassDarA
and the call to superclass?ethodA76 occur in #ubclass<. 'hese members are declared in
#uperclassA. #ubclass< is not involved in the implementation of a #uperclassA, !hich is the type
of ob/IefA. 8ence access to protected members at lines (6) and (:) is not permitted as these are
not members of an ob)ect that can be guaranteed to be implemented by the code accessing them.
%ccessibility to protected members of the superclass !ould be permitted via any references of
subclasses of #ubclass<. 'he above restriction helps to ensure that subclasses in packages
different from their superclass can only access protected members of the superclass in their part of
the implementation inheritance hierarchy.
De)ault Accessibility )or $embers
When no member accessibility modifier is specified, the member is only accessible by other classes
in its classGs package. +ven if its class is visible in another (possibly nested) package, the member
is not accessible there. Default member accessibility is more restrictive than protected member
accessibility.
"n +&le 6.<, if the field superclassDarA and the method superclass ?ethodA are defined !ith
no accessibility modifier, then they are only accessible !ithin package packageA, but not in any
other (possibly nested) packages.
public class #uperclassA 0
int superclassDarA; '' 7*6
"oid superclass?ethodA76 0'C---C'1 '' 7)6
1
'he clients in package package< (i.e. Hlients / and 6) cannot access these members. 'his situation
is depicted in igure 6.1.
Figure 4.6. 6efault A!!essi$ility
private $embers
'his is the most restrictive of all the accessibility modifiers. .rivate members are not accessible
from any other class. 'his also applies to subclasses, !hether they are in the same package or not.
Since they are not accessible by simple name in a subclass, they are also not inherited by the
subclass. 'his is not to be confused !ith the e&istence of such a member in the state of an ob)ect
of the subclass (see Section ;.0, p. /60). % standard design strategy is to make all fields private,
and provide public accessor methods for them. %u&iliary methods are often declared private, as
they do not concern any client.
"n +&le 6.<, if the field superclassDarA and the method superclass ?ethodA have private
accessibility, then they are not accessible by any other clients.
public class #uperclassA 0
pri"ate int superclassDarA; '' 7*6
pri"ate "oid superclass?ethodA76 0'C---C'1 '' 7)6
1
3one of the clients in igure 6.= can access these members.
Figure 4.7. /ri3ate A!!essi$ility
#a$le 4.4. )ummary of A!!essi$ility Modifiers for Mem$ers
Modifiers Mem$ers
public
%ccessible every!here.
protected
%ccessible by any class in the same package as its class, and accessible only by
subclasses of its class in other packages.
default (no
modifier)
5nly accessible by classes, including subclasses, in the same package as its class
(package accessibility).
pri"ate
5nly accessible in its o!n class and not any!here else.
%evie& 'uestions
4.177iven the follo!ing definition of a class, !hich fields are accessible from outside the package
com-corporation-pro/ect@
package com-corporation-pro/ect;
public class ?y=lass 0
int i;
public int /;
protected int k;
pri"ate int l;
1
Select the t!o correct ans!ers.
a. ield i is accessible in all classes in other packages.
b. ield / is accessible in all classes in other packages.
c. ield k is accessible in all classes in other packages.
d. ield k is accessible in subclasses only in other packages.
e. ield l is accessible in all classes in other packages.
f. ield l is accessible in subclasses only in other packages.
4.1,8o! restrictive is the default accessibility compared to public, protected, and pri"ate
accessibility@
Select the one correct ans!er.
a. Dess restrictive than public.
b. ?ore restrictive than public, but less restrictive than protected.
c. ?ore restrictive than protected, but less restrictive than pri"ate.
d. ?ore restrictive than pri"ate.
e. Dess restrictive than protected from !ithin a package, and more restrictive than
protected from outside a package.
4.1-Which statement is true about accessibility of members@
Select the one correct ans!er.
a. .rivate members are al!ays accessible from !ithin the same package.
b. .rivate members can only be accessed by code from !ithin the class of the member.
c. % member !ith default accessibility can be accessed by any subclass of the class in
!hich it is defined.
d. .rivate members cannot be accessed at all.
e. .ackageIdefault accessibility for a member can be declared using the key!ord default.
4.16 Other $odi)iers )or $embers
Hertain characteristics of fields andIor methods can be specified in their declarations by the
follo!ing key!ords2
static
final
abstract
synchronized
nati"e
transient
"olatile
static $embers
'he declaration of static members is prefi&ed by the key!ord static to distinguish them from
instance members.
Static members belong to the class in !hich they are declared, and are not part of any instance of
the class. Depending on the accessibility modifiers of the static members in a class, clients can
access these by using the class name, or through ob)ect references of the class. 'he class need not
be instantiated to access its static members.
Static variables (also called class varia"les) only e&ist in the class they are defined in. 'hey are not
instantiated !hen an instance of the class is created. "n other !ords, the values of these variables
are not a part of the state of any ob)ect. When the class is loaded, static variables are initialized to
their default values if no e&plicit initialization e&pression is specified (see Section ;.0, p. //1).
Static methods are also kno!n as class methods. % static method in a class can directly access
other static members in the class. "t cannot access instance (i.e., non$static) members of the class,
as there is no notion of an ob)ect associated !ith a static method. 8o!ever, note that a static
method in a class can al!ays use a reference of the classGs type to access its members, regardless
of !hether these members are static or not.
% typical static method might perform some task on behalf of the !hole class andIor for ob)ects of
the class. "n +&le 6.-,, the static variable counter keeps track of the number of instances of
the Light class created. 'he e&le sho!s that the static method write=ount can only access
static members directly, as sho!n at (0), but not non$static members, as sho!n at (/). 'he static
variable counter !ill be initialized to the value !hen the class is loaded at runtime. 'he main76
method at (6) in class Karehouse sho!s ho! static members of class Light can be accessed using
the class name, and via ob)ect references having the class type.
% summary of ho! static members are accessed in static and non$static code is given in 'able 6.-.
Example 4.1. A!!essing )tati! Mem$ers
class Light 0
'' Bields
int no.fKatts; '' wattage
boolean indicator; '' on or off
#tring location; '' placement
'' #tatic "ariable
static int counter; '' !o- of Light ob/ects created- 7&6
'' $%plicit +efault =onstructor
Light76 0
no.fKatts = (;
indicator = true;
location = 9G9;
AAcounter; '' Increment counter-
1
'' #tatic method
public static "oid write=ount76 0
#ystem-out-println79!umber of lights, 9 A counter6; '' 7*6
'' =ompile error- Bield no.fKatts is not accessible,
'' #ystem-out-println79!umber of Katts, 9 A no.fKatts6; '' 7)6
1
1
public class Karehouse 0
public static "oid main7#tring[] args6 0 '' 726
Light-write=ount76; '' In"oked using class name
Light aLight = new Light76; '' =reate an ob/ect
#ystem-out-println7
9Dalue of counter, 9 A Light-counter '' Accessed "ia class name
6;
Light bLight = new Light76; '' =reate another ob/ect
bLight-write=ount76; '' In"oked using reference
Light cLight = new Light76; '' =reate another ob/ect
#ystem-out-println7
9Dalue of counter, 9 A cLight-counter '' Accessed "ia reference
6;
1
1
5utput from the program2
!umber of lights,
Dalue of counter, &
!umber of lights, *
Dalue of counter, )
final $embers
% final variable is a constant, despite being called a variable. "ts value cannot be changed once it
has been initialized. 'his applies to instance, static and local variables, including parameters that
are declared final.
% final variable of a primitive data type cannot change its value once it has been
initialized.
% final variable of a reference type cannot change its reference value once it has been
initialized, but the state of the ob)ect it denotes can still be changed.
'hese variables are also kno!n as "lan# final varia"les. inal static variables are commonly used to
define manifest constants (also called named constants), for e&le Integer-?AGQDALO$, !hich is
the ma&imum int value. Eariables defined in an interface are implicitly final (see Section 1.6, p.
0:-). 3ote that a final variable need not be initialized at its declaration, but it must be initialized
once before it is used. or a discussion on final parameters, see Section /.00, p. <6.
% final method in a class is complete (i.e., has an implementation) and cannot be overridden in
any subclass (see Section 1.0, p. 0//). Subclasses are then restricted in changing the behavior of
the method.
inal variables ensure that values cannot be changed, and final methods ensure that behavior
cannot be changed. inal classes are discussed in Section 6.;.
'he compiler is able to perform certain code optimizations for final members, because certain
assumptions can be made about such members.
"n +&le 6.--, the class Light defines a final static variable at (-) and a final method at (0).
%n attempt to change the value of the final variable at (/) results in a compile$time error. 'he
subclass 8ubeLight attempts to override the final method setKatts76 from the superclass Light
at (6), !hich is not permitted. 'he class Karehouse defines a final local reference aLight at (:).
'he state of the ob)ect denoted by aLight can be changed at (1), but its reference value cannot be
changed as attempted at (=).
Example 4.11 A!!essing Final Mem$ers
class Light 0
'' Binal static "ariable 7&6
final public static double NK>QPII=$ = )-*(;
int no.fKatts;
'' Binal instance method 7*6
final public "oid setKatts7int watt6 0
no.fKatts = watt;
1
public "oid setNK>76 0
'' NK>QPII=$ = 2-&; '' 7)6 !ot .N- =annot be changed-
1
1
class 8ubeLight e%tends Light 0
'' Binal method in superclass cannot be o"erridden-
'' 8his method will not compile-
'C
public "oid setKatts7int watt6 0 '' 726 Attempt to o"erride-
no.fKatts = *Cwatt;
1
C'
1
public class Karehouse 0
public static "oid main7#tring[] args6 0
final Light aLight = new Light76;'' 7(6 Binal local "ariable-
aLight-no.fKatts = &; '' 746 .N- =hanging ob/ect state-
'' aLight = new Light76; '' 756 !ot .N- =hanging final reference-
1
1
abstract $ethods
%n abstract method has the follo!ing synta&2
abstract <accessi"ility modifier >return typeJ >method nameJ 7>parameter listJ6
>thro$s clauseJ;
%n abstract method does not have an implementation9 that is, no method body is defined for an
abstract method, only the method prototype is provided in the class definition. "ts class is then
abstract (i.e., incomplete) and must be e&plicitly declared as such (see Section 6.;, p. -/6).
Subclasses of an abstract class must then provide the method implementation9 other!ise, they
are also abstract. See Section 6.;, !here +&le 6.; also illustrates the usage of abstract
methods.
5nly an instance method can be declared abstract. Since static methods cannot be overridden,
declaring an abstract static method !ould make no sense. % final method cannot be abstract
(i.e., cannot be incomplete) and vice versa. 'he key!ord abstract cannot be combined !ith any
nonaccessibility modifiers for methods. ?ethods specified in an interface are implicitly abstract, as
only the method prototypes are defined in an interface (see Section 1.6, p. 0:-).
synchronized $ethods
Several threads can be e&ecuting in a program (see Section <.6, p. /:<). 'hey might try to e&ecute
several methods on the same ob)ect simultaneously. "f it is desired that only one thread at a time
can e&ecute a method in the ob)ect, the methods can be declared synchronized. 'heir e&ecution is
then mutually e&clusive among all threads. %t any given time, at the most one thread can be
e&ecuting a synchronized method on an ob)ect. 'his discussion also applies to static
synchronized methods of a class.
"n +&le 6.-0, both the push76 and the pop76 methods are synchronized in class #tackImpl.
3o!, only one thread at a time can e&ecute a synchronized method in an ob)ect of the class
#tackImpl. 'his means that it is not possible for the state of an ob)ect of the class #tackImpl to be
corrupted, for e&le, !hile one thread is pushing an element and another is popping the stack.
Example 4.12 )yn!&roni7ed Met&ods
class #tackImpl 0
pri"ate .b/ect[] stackArray;
pri"ate int top.f#tack;
'' ---
synchronized public "oid push7.b/ect elem6 0 '' 7&6
stackArray[AAtop.f#tack] = elem;
1
synchronized public .b/ect pop76 0 '' 7*6
.b/ect ob/ = stackArray[top.f#tack];
stackArray[top.f#tack] = null;
top.f#tack;;;
return ob/;
1
'' .ther methods, etc-
public .b/ect peek76 0 return stackArray[top.f#tack]; 1
1
native $ethods
3ative methods are also called foreign methods. 'heir implementation is not defined in (ava but in
another programming language, for e&le, H or HKK. Such a method can be declared as a
member in a (ava class definition. Since its implementation appears else!here, only the method
prototype is specified in the class definition. 'he method prototype is prefi&ed !ith the key!ord
nati"e. "t can also specify checked e&ceptions in a throws clause, !hich cannot be checked by the
compiler since the method is not implemented in (ava. 'he ne&t e&le sho!s ho! native
methods are used.
'he (ava 3ative "nterface ((3") is a special %." that allo!s (ava methods to invoke native functions
implemented in H.
"n the follo!ing e&le, a nati"e method in class !ati"e is declared at (0). 'he class also uses a
static initializer block (see Section ;.0, p. //1) at (-) to load the native library !hen the class is
loaded. Hlients of the !ati"e class can call the nati"e method like any another method, as at (/).
class !ati"e 0
'C
C 8he static block ensures that the nati"e method library
C is loaded before the nati"e method is called-
C'
static 0
#ystem-loadLibrary79!ati"e?ethodLib96; '' 7&6 Load nati"e library-
1
nati"e "oid nati"e?ethod76; '' 7*6 !ati"e method prototype-
'' ---
1
class =lient 0
''---
public static "oid main7#tring[] args6 0
!ati"e a!ati"e = new !ati"e76;
a!ati"e-nati"e?ethod76; '' 7)6 !ati"e method call-
1
''---
1
transient 7ields
5b)ects can be stored using serialization. Serialization transforms ob)ects into an output format
that is conducive for storing ob)ects. 5b)ects can later be retrieved in the same state as !hen they
!ere serialized, meaning that all fields included in the serialization !ill have the same values as at
the time of serialization. Such ob)ects are said to be persistent.
% field can be specified as transient in the class declaration, indicating that its value should not be
saved !hen ob)ects of the class are !ritten to persistent storage. "n the follo!ing e&le, the
field current8emperature is declared transient at (-), because the current temperature is most
likely to have changed !hen the ob)ect is restored at a later date. 8o!ever, the value of the field
mass, declared at (0), is likely to remain unchanged. When ob)ects of the class $%periment are
serialized, the value of the field current8emperature !ill not be saved, but that of the field mass
!ill be as part of the state of the serialized ob)ect.
class $%periment implements #erializable 0
'' ---
'' 8he "alue of current8emperature will not persist
transient int current8emperature; '' 7&6 8ransient "alue-
double mass; '' 7*6 Persistent "alue-
1
Specifying the transient modifier for static variables is redundant and, therefore, discouraged.
Static variables are not part of the persistent state of a serialized ob)ect.
volatile 7ields
During e&ecution, compiled code might cache the values of fields for efficiency reasons. Since
multiple threads can access the same field, it is vital that caching is not allo!ed to cause
inconsistencies !hen reading and !riting the value in the field. 'he "olatile modifier can be used
to inform the compiler that it should not attempt to perform optimizations on the field, !hich could
cause unpredictable results !hen the field is accessed by multiple threads.
"n the simple e&le that follo!s, the value of the field clockIeading might be changed
une&pectedly by another thread !hile one thread is performing a task that involves al!ays using
the current value of the field clockIeading. Declaring the field as "olatile ensures that a !rite
operation !ill al!ays be performed on the master field variable, and a read operation !ill al!ays
return the correct current value.
class Dital=ontrol 0
'' ---
"olatile long clockIeading;
'' 8wo successi"e reads might gi"e different results-
1
#a$le 4.5. )ummary of 4t&er Modifiers for Mem$ers
Modifiers Fields Met&ods
static
Defines a class variable. Defines a class method.
final
Defines a constant. 'he method cannot be overridden.
abstract
3ot relevant. 3o method body is defined. "ts class
must also be designated abstract.
synchronized
3ot relevant. 5nly one thread at a time can e&ecute
the method.
nati"e
3ot relevant. Declares that the method is implemented
in another language.
transient
'he value in the field !ill not be
included !hen the ob)ect is serialized.
3ot applicable.
"olatile
'he compiler !ill not attempt to
optimize access to the value in the field.
3ot applicable.
%evie& 'uestions
4.2.Which statements are true about the use of
modifiers@
Select the t!o correct ans!ers.
a. "f no accessibility modifier (public,
protected, and pri"ate) is specified for a
member declaration, the member is only
accessible for classes in the package of its
class and subclasses of its class any!here.
b. Aou cannot specify accessibility of local
variables. 'hey are only accessible !ithin the
block in !hich they are declared.
c. Subclasses of a class must reside in the same
package as the class they e&tend.
d. Docal variables can be declared static.
e. 5b)ects themselves do not have any
accessibility modifiers, only the ob)ect
references do.
4.217iven the follo!ing source code, !hich comment
line can be uncommented !ithout introducing
errors@
abstract class ?y=lass 0
abstract "oid f76;
final "oid g76 01
'' final "oid h76 01
'' 7&6
protected static int i;
pri"ate int /;
1
final class ?y.ther=lass e%tends ?y=lass 0
'' ?y.ther=lass7int n6 0 m = n; 1
'' 7*6
public static "oid main7#tring[] args6 0
?y=lass mc = new ?y.ther=lass76;
1
"oid f76 01
"oid h76 01
'' "oid k76 0 iAA; 1
'' 7)6
'' "oid l76 0 /AA; 1
'' 726
int m;
1
Select the one correct ans!er.
a-
b- final "oid h76 01
'' 7&6
!.
d-
e- ?y.ther=lass7int n6 0 m = n; 1
'' 7*6
f.
g-
h- "oid k76 0 iAA; 1
'' 7)6
i.
/-
k- "oid l76 0 /AA; 1
'' 726
l.
4.22What !ould be the result of attempting to compile
and run the follo!ing program@
class ?y=lass 0
static ?y=lass ref;
#tring[] arguments;
public static "oid main7#tring[] args6 0
ref = new ?y=lass76;
ref-func7args6;
1
public "oid func7#tring[] args6 0
ref-arguments = args;
1
1
Select the one correct ans!er.
a. 'he program !ill fail to compile, since the
static method main76 cannot have a call to
the non$static method func76.
b. 'he program !ill fail to compile, since the
non$static method func76 cannot access the
static variable ref.
c. 'he program !ill fail to compile, since the
argument args passed to the static method
main76 cannot be passed on to the non$static
method func76.
d. 'he program !ill fail to compile, since the
method func76 cannot assign the value of
the static variable ref to the non$static
variable arguments.
e. 'he program !ill compile, but !ill thro! an
e&ception !hen run.
f. 'he program !ill compile and run
successfully.
4.237iven the follo!ing member declarations, !hich
statement is true@
int a; '' 7&6
static int a; '' 7*6
int f76 0 return a; 1 '' 7)6
static int f76 0 return a; 1 '' 726
Select the one correct ans!er.
a. Declarations (-) and (/) cannot occur in the
same class definition.
b. Declarations (0) and (6) cannot occur in the
same class definition.
c. Declarations (-) and (6) cannot occur in the
same class definition.
d. Declarations (0) and (/) cannot occur in the
same class definition.
4.24Which statement is true@
Select the one correct ans!er.
a. % static method can call other non$static
methods in the same class by using the this
key!ord.
b. % class may contain both static and non$
static variables and both static and non$static
methods.
c. +ach ob)ect of a class has its o!n instance of
each static variable.
d. "nstance methods may access local variables
of static methods.
e. %ll methods in a class are implicitly passed a
this parameter !hen called.
4.25What, if anything, is !rong !ith the follo!ing code@
abstract class ?y=lass 0
transient int /;
synchronized int k;
final "oid ?y=lass76 01
static "oid f76 01
1
Select the one correct ans!er.
a. 'he class ?y=lass cannot be declared
abstract.
b. 'he field / cannot be declared transient.
c. 'he field k cannot be declared synchronized.
d. 'he method ?y=lass76 cannot be declared
final.
e. 'he method f76 cannot be declared static.
f. 3othing is !rong !ith the code9 it !ill
compile !ithout errors.
4.26Which one of these is not a legal member
declaration !ithin a class@
Select the one correct ans!er.
a. static int a;
b. final .b/ect[] fudge = 0 null 1;
c. abstract int t;
d. nati"e "oid sneeze76;
e. final static pri"ate double PI =
)-&2&(3*4()(E353)*)E24;
4.27Which statements are true about modifiers@
Select the t!o correct ans!ers.
a. %bstract classes can contain final methods.
b. ields can be declared nati"e.
c. 3on$abstract methods can be declared in
abstract classes.
d. Hlasses can be declared nati"e.
e. %bstract classes can be declared final.
4.2,Which statement is true@
Select the one correct ans!er.
a. 'ransient fields !ill not be saved during
serialization.
b. Honstructors can be declared abstract.
c. 'he initial state of an array ob)ect
constructed !ith the statement int[] a =
new int[&] !ill depend on !hether the
array variable a is a local variable or a field.
d. % subclass of a class !ith an abstract
method must provide an implementation for
the abstract method.
e. 5nly static methods can access static
members.
Chapter Summary
'he follo!ing information !as included
in this chapter2
e&planation of declaration,
construction, initialization, and
usage of both one$ and multi$
dimensional arrays, including
anonymous arrays
defining classes
defining methods, usage of the
this reference in an instance
method, and method overloading
defining constructors, usage of
the default constructor, and
overloading of constructors
defining and using packages
discussion of accessibility
(default, public) and other
modifiers (abstract, final) for
classes and interfaces
e&planation of class scope for
members, and block scope for
local variables
applicability of member
accessibility (default, public,
protected, pri"ate) and other
member modifiers (static,
final, abstract, synchronized,
nati"e, transient, "olatile)
0rogramming Exercises
4.1"magine you are creating an application that has a number of different tools a user may invoke.
'hese tools need a special conte&t to !ork in. 'he conte&t describes the current active selection
in the application. 'he selection consists of a reference to an arbitrary ob)ect. We !ish to create
a class representing an editing conte&t that the tools may use. 'his class should contain the
aforementioned selection reference. We do not !ant to allo! direct manipulation of the
reference, but !ant to have methods in the conte&t class that allo! anyone to get and set the
current selection.
Write such a class. Ce sure to get the accessibility right.
4.2% !ide variety of tools can e&ist in an application, as described in +&ercise 6.-. What they all
have in common is that they can all be given an instance of an editing conte&t, and that they are
in either an active or an inactive state.
Write an interface that contains methods for giving the tool an editing conte&t instance and
querying the tool !hether it is active or not.
4.3Design a class for a bank database. 'he database should support the follo!ing operations2
depositing a certain amount into an account
!ithdra!ing a certain amount from an account
looking up the current amount (i.e. the balance) in an account
transferring an amount from one account to another
'he amount in the transactions is a value of type long. 'he accounts are identified by instances
of the class Account that resides in a package called com-megabankcorp- records. 'he
database ob)ect should reside in a package called com-megabankcorp- system.
'he depositing, !ithdra!ing, and balancing operations should not have any implementation, but
allo! subclasses to provide the implementation. 'he transferring operation should use the
depositing and !ithdra!ing operations to implement the transfer. "t should not be possible to
alter this operation in any subclass, and only classes !ithin the package
com-megabankcorp-system should be allo!ed to use this operation. 'he depositing and
!ithdra!ing operations should be available from any!here. 'he balancing operation should only
be available from subclasses and classes !ithin the package com-megabankcorp-system.