Sei sulla pagina 1di 57

Page 1 of 57

Chapter 4. Declarations and Access Control


Exam Objectives

! "
public final static abstract! #

" $

% &

'

Supplementary Objectives

( this

( &

' ) &

# & package import "


"

4.1 Arrays
* + +
*
) *
+ +

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


Page 2 of 57

' , - * '
'
. -
/ - final length &

& +0 + )1 & length

# $ #
- - - &

2 # 340
# 55

Declaring Array Variables


* & +6

[] ;

[];

&
[] 7

' '
-

int anIntArray[], oneInteger;


Pizza[] mediumPizzas, largePizzas;

& anIntArray mediumPizzas


int Pizza - largePizzas
oneInteger int 8
int

[] & 9 & []
&

*
& null
#
4: 33! &

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


Page 3 of 57

Constructing an Array
* new

= new [ ! ];

! 0 &
, ! ' NegativeArraySizeException &

; & 6

int anIntArray[], oneInteger;


Pizza[] mediumPizzas, largePizzas;

&6

anIntArray = new int[10]; // array for 10 integers


mediumPizzas = new Pizza[5]; // array of 5 pizzas
largePizzas = new Pizza[3]; // array of 3 pizzas

1
[] = new 2
[ ! ];

<& 2
[] " 1
[] # 55 450!
2 &

' + &
% + +2 anIntArray
0 +3 mediumPizzas null &

int[] anIntArray = new int[10]; // Default element value: 0.

Pizza[] mediumPizzas = new Pizza[5]; // Default element value: null.

// Pizza class extends Object class


Object objArray = new Pizza[3]; // Default element value: null.

// Pizza class implements Eatable interface


Eatable[] eatables = new Pizza[2]; // Default element value: null.

length
= + medium Pizzas.length 5

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


Page 4 of 57

9 + =
+ /+ "

Initializing an Array
, +
6

[] = { ! };

& !
) + # "

int[] anIntArray = {1, 3, 49, 2, 6, 7, 15, 2, 1, 5};

anIntArray int ' 10 $


+ "! &
+ 1) + 3)

// Pizza class extends Object class


Object[] objArray = { new Pizza(), new Pizza(), null };

objArray Object
& & Pizza
- & null 7 -
6 - &
& Pizza -

+ !
+ ' +
! " } "
& & 6

Topping[] pizzaToppings = { new Topping("cheese"), new Topping("tomato"), };

1! & String -
& 4! " String -
char

// Array with 4 String objects


String[] pets = {"crocodiles", "elephants", "crocophants", "elediles"}; // (1)

// Array of 3 characters
char[] charArray = {'a', 'h', 'a'}; // (2) Not the same as "aha".

Using an Array
&
+& [] + &

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


Page 5 of 57

+6

[ ]

/
& + ) int
# & & 0
.length-1! i +(i-1) *
+ " & +
' + 0 $ length
+ ArrayIndexOutOfBoundsException & *
" + + + # >> 1?1!
+

' + +
% + & + &
+1 toCharArray() String
6 "AHA".toCharArray()[1]

[] Topping[]! new
Toppings[3]! toppings[1]! &
+ # 55
450! & #
340 @1!

/+ :1 & 3! trialArray
4! & ) 0.0 100.0!
randomize() >! findMinimum
() 5! storeMinimum 1! :!
0
& =
+&

class Trials {
public static void main(String[] args) {
// Declare and construct the local arrays
double[] storeMinimum = new double[5]; // (1)
double[] trialArray = new double[15]; // (2)
for (int i = 0; i < storeMinimum.length; ++i) { // (3)
// Initialize the array
randomize(trialArray);
// Find and store the minimum value
storeMinimum[i] = findMinimum(trialArray);
}
// Print the minimum values (4)
for (int i = 0; i < storeMinimum.length; ++i)
System.out.println(storeMinimum[i]);
}

public static void randomize(double[] valArray) { // (5)


for (int i = 0; i < valArray.length; ++i)
valArray[i] = Math.random() * 100.0;

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


Page 6 of 57

public static double findMinimum(double[] valArray) { // (6)


// Assume the array has at least one element.
double minValue = valArray[0];
for (int i = 1; i < valArray.length; ++i)
minValue = Math.min(minValue, valArray[i]);
return minValue;
}
}

2 6

6.756931310985048
5.364063199341363
8.359410202984296
8.858272848258109
9.759950059619849

Anonymous Arrays
* & &

1
[] = new 2
[ ! ]; // (1)
int[] intArray = new int[5];

+
+ &
9 &

[] = { ! }; // (2)
int[] intArray = {3, 5, 2, 8, 6};

"<& " +

, + & &
+ 1! " 4!
- 6

new [] { ! }
new int[] {3, 5, 2, 8, 6}

' & & +


$

int[] intArray = {3, 5, 2, 8, 6}; // (1)


int[] intArray = new int[] {3, 5, 2, 8, 6}; // (2)

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


Page 7 of 57

' 1! " ' 4!


+ ' " + =
+
<& 8 +

int[] daysInMonth;
daysInMonth = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; // Not ok.
daysInMonth = new int[] {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; // ok.

# A>
30?!6

' /+ :4 1!
findMinimum() 4! 7

class AnonArray {
public static void main(String[] args) {
System.out.println("Minimum value: " +
findMinimum(new int[] {3, 5, 2, 8, 6})); // (1)
}

public static int findMinimum(int[] dataSeq) { // (2)


// Assume the array has at least one element.
int min = dataSeq[0];
for (int index = 1; index < dataSeq.length; ++index)
if (dataSeq[index] < min)
min = dataSeq[index];
return min;
}
}

9 6

Minimum value: 2

Multidimensional Arrays

# - -
' , &6

[][]...[] ;

[][]...[];

' $ $ " []
+ *

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


Page 8 of 57

& $ 6

int[][] mXnArray; // 2-dimensional array


int[] mXnArray[]; // 2-dimensional array
int mXnArray[][]; // 2-dimensional array

' &

int[][] mXnArray = new int[4][5]; // 4 x 5 matrix of ints

mXnArray &
&! 5 int &
4) & <&
,

/ & + mXnArray[i] & 0 i B 4. /

i & mXnArray[i] mXnArray[i][j] & 0 j B 5. &


mXnArray.length 4 i &
mXnArray[i].length 5 & & 0 iB4

C +
" 7 & &
" 6

double[][] identityMatrix = {
{1.0, 0.0, 0.0, 0.0 }, // 1. row
{0.0, 1.0, 0.0, 0.0 }, // 2. row
{0.0, 0.0, 1.0, 0.0 }, // 3. row
{0.0, 0.0, 0.0, 1.0 } // 4. row
}; // 4 x 4 Floating-point matrix

*
pizzaGalore && & &
&

Pizza[][] pizzaGalore = {
{ new Pizza(), null, new Pizza() }, // 1. row is an array of 3 elements.
{ null, new Pizza()}, // 2. row is an array of 2 elements.
new Pizza[1], // 3. row is an array of 1 element.
{}, // 4. row is an array of 0 elements.
null // 5. row is not constructed.
};

& new
' % +
HotelRoom[]
[][][] % $ "
:) &

HotelRoom[][][][] rooms = new HotelRoom[10][5][][]; // Just streets and hotels.

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


Page 9 of 57

rooms & &


% 6

rooms[0][0] = new HotelRoom[3][]; // 3 floors in 1st. hotel on 1st. street.


rooms[0][0][0] = new HotelRoom[8]; // 8 rooms on 1st. floor in this hotel.
rooms[0][0][0][0] = new HotelRoom(); // Initialize 1st. room on this floor.

& matrix & &


& & & 7

& & double


0.0D! ' % :1 matrix
+

double[][] matrix = new double[3][]; // No. of rows.

for (int i = 0; i < matrix.length; ++i)


matrix[i] = new double[i + 1]; // Construct a row.

& & "


& &6

double[][] matrix2 = {
{0.0}, // 1. row
{0.0, 0.0}, // 2. row
{0.0, 0.0, 0.0} // 3. row
}

double[][] matrix3 = new double[][] {


{0.0}, // 1. row
{0.0, 0.0}, // 2. row
{0.0, 0.0, 0.0} // 3. row
}

matrix double[][] & ) double !


matrix[i] & 0 iB matrix.length! double[] )
double ! matrix[i][j] & 0 iB matrix.length 0

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


Page 10 of 57

jB matrix[i].length! double double)

7 ' /+ :3
:+3int + 1!

+ 4! & mXnArray[i] 0 iB
mXnArray.length! 3! & mXnArray

[i][j] 0 jB mXnArray[i].length! + mXnArray.length :


+ mXnArray.length! + mXnArray[i].length! 14
& 3

class MultiArrays {

public static void main(String[] args) {


// Declare and construct the M X N matrix.
int[][] mXnArray = { // (1)
{16, 7, 12}, // 1. row
{ 9, 20, 18}, // 2. row
{14, 11, 5}, // 3. row
{ 8, 5, 10} // 4. row
}; // 4 x 3 int matrix

// Find the minimum value in a M X N matrix


int min = mXnArray[0][0];
for (int i = 0; i < mXnArray.length; ++i) // (2)
// Find min in mXnArray[i], i.e. in the row given by index i.
for (int j = 0; j < mXnArray[i].length; ++j) // (3)
min = Math.min(min, mXnArray[i][j]);
System.out.println("Minimum value: " + min);
}
}

9 6

Minimum value: 5

Review Questions

; & & +
D

int[] array;

# &

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


Page 11 of 57

array[].length()

array.length()

array[].length

array.length

array[].size()

array.size()

' D

# &

E &

E -

7 ) main()
) String &

7 ,

& D

# &

int []a[] = new int [4][4];

int a[][] = new int [4][4];

int a[][] = new int [][4];

int []a[] = new int [4][];

int [][]a = new int [4][4];

# & &

int[] i[] = { { 1, 2 }, { 1 }, {}, { 1, 2, 3 } };

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


Page 12 of 57

int i[] = new int[2] {1, 2};

int i[][] = new int[][] { {1, 2, 3}, {4, 5, 6} };

int i[][] = { { 1, 2 }, new int[ 2 ] };

int i[4] = { 1, 2, 3, 4 };

& & D

// Filename: MyClass.java
class MyClass {
public static void main(String[] args) {
int size = 20;
int[] arr = new int[ size ];

for (int i = 0; i < size; ++i) {


System.out.println(arr[i]);
}
}
}

# &

& int[]

& & & ArrayIndexOutOfBoundsException


&

& & &

& & & 0


1@

& & & 0 &

& & & null &

; & & D

class MyClass {
public static void main(String[] args) {
String[] numbers = { "one", "two", "three", "four" };

if (args.length == 0) {
System.out.println("no arguments");
} else {
System.out.println(numbers[ args.length ] + " arguments");
}
}
}

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


Page 13 of 57

# &

&

& & NullPointerException & &

& "no arguments" "two arguments" & &

& "no arguments" "three arguments" & &

& "no arguments" "four arguments" & &

& "one arguments" "four arguments" & &

! & & D

public class DefaultValuesTest {


int[] ia = new int[1];
boolean b;
int i;
Object o;

public static void main(String[] args) {


DefaultValuesTest instance = new DefaultValuesTest();
instance.print();
}

public void print() {


System.out.println(ia[0] + " " + b + " " + i + " " + o);
}
}

# &

&

& & java.lang.NullPointerException &

& F
0 false NaN nullF

& F
0 false 0 nullF

& F
null 0 0 nullF

& F
null false 0 nullF

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


Page 14 of 57

4.2 Defining Classes


* & ' & +6

class
// Class header
{ // Class body

! " #
}

' " & class '


& 6

" # :A 131!

# :? 13:!

# 51 445!

# 5: 4>1!

" &

# 43 31!

# :3 114!

# A1 4?:!

C static " )
- " '
& 6

# :: 11A!

! " # # ?4 331!

"

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


Page 15 of 57

' & & &


* +
" * ) + )
" & +
+ & +
) + 9 & & +
)

4.3 Defining Methods


+

( )
$ // Method prototype
{ // Method body
"

' &
6

" # :> 141!

# :10 1::!

void #
>: 1A5!

# & throws # >@ 401!

)
& " # 31A ?5! *
( ) /
6

# :> 143!
final # 344 @:

" #

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


Page 16 of 57

% " # 43 31
# A: 304

" 6

&

# :10 1::! &

Statements
# , G & +
# 43 31 #
:1 104! 9 $ # >1 1>?!

* + +
9 +
& 6

# 3: :A!

# 3A 53!

# 31A ?5!

- + & new # 315 ?:!

* " {} &
# :> 143! " "
* " +&
& " {
& } # " &
" # :1 104!

# >: 1A1

Instance Methods and Object Reference this

' - " - *
) +

"& - & " -


" & this '
this " - - '
" & this ) + this
-

this - &

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


Page 17 of 57

$ & ' /+ :: & noOfWatts


indicator Light
+ location &
this * 1!
this noOfWatts &
noOfWatts this 4! indicator
" #
3! & this location
site

this "

class Light {
// Fields
int noOfWatts; // wattage
boolean indicator; // on or off
String location; // placement

// Constructor
public Light(int noOfWatts, boolean indicator, String site) {
String location;

this.noOfWatts = noOfWatts; // (1) Assignment to field.


indicator = indicator; // (2) Assignment to parameter.
location = site; // (3) Assignment to local variable.
this.superfluous(); // (4)
superfluous(); // equivalent to call at (4)
}

public void superfluous() { System.out.println(this); } // (5)

public static void main(String[] args) {


Light light = new Light(100, true, "loft");
System.out.println("No. of watts: " + light.noOfWatts);
System.out.println("Indicator: " + light.indicator);
System.out.println("Location: " + light.location);
}
}

9 6

Light@df6ccd
Light@df6ccd
No. of watts: 100
Indicator: false
Location: null

' & member


) this.member ' this +
" :! /+ :: &
superfluous()

' -
this >! /+ :: & -
println()

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


Page 18 of 57

7 this + +
+ -

Method Overloading
/ &
#
#

. & &
$ , 4# H *2' "
% + java.lang.Math min() &
&

public static double min(double a, double b)


public static float min(float a, float b)
public static int min(int a, int b)
public static long min(long a, long b)

' & + methodA & 6

void methodA(int a, double b) { /* ... */ } // (1)


int methodA(int a) { return a; } // (2)
int methodA() { return 1; } // (3)
long methodA(double a, int b) { return b; } // (4)
long methodA(int x, double y) { return x; } // (5) Not OK.

&6

methodA(int, double) 1I
methodA(int) 4I
67
methodA() 3I
67
methodA(double, int) :I
69
methodA(int, double) >I
6# 1I

methodA
& >!
methodA(int, double) 1!

void bake(Cake k) { /* ... */ } // (1)


void bake(Pizza p) { /* ... */ } // (2)

int halfIt(int a) { return a/2; } // (3)


double halfIt(int a) { return a/2.0; } // (4) Not OK. Same signature.

bake 1! 4! & & '


- & 3! :!!
& )
9

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


Page 19 of 57

- C & &
*
# 54
43A 9
C &
# 54 433!

4.4 Constructors
- & -
new

* & +6

" ( )
$ // Constructor header
{ // Constructor body
"

J " <& &


6

C
* # :A 131

J void
return

J +
/+ :> & 4!
1! < &

public class Name {

Name() { // (1)
System.out.println("Constructor");
}

void Name() { // (2)


System.out.println("Method");
}
public static void main(String[] args) {

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


Page 20 of 57

new Name().Name(); // (3) Constructor call followed by method call.


}
}

9 6

Constructor
Method

Default Constructor
* & ' & &
6

()

'
$ & 6

() { super(); } // No parameters. Calls superclass constructor.

"
- # 53 4:3! '
-

' & Light

class Light {
// Fields
int noOfWatts; // wattage
boolean indicator; // on or off
String location; // placement

// No constructors
//...
}

class Greenhouse {
// ...
Light oneLight = new Light(); // (1) Call of implicit default constructor.
}

' & & Light -


1!6

Light() { super(); }

J - new & 1! &


- noOfWatts indicator
location Light - & 0 false null !

* ' &

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


Page 21 of 57

+ Light + 1! 7
"

class Light {
// ...
// Explicit Default Constructor
Light() { // (1)
noOfWatts = 50;
indicator = true;
location = "X";
}
//...
}

class Greenhouse {
// ...
Light extraLight = new Light(); // (2) Call of explicit default constructor.
}

+ - & + new Light()


4! & noOfWatts indicator location 50 true "X"

' +
- ' $
' + & Light )
1! ' 4! & - Light & new *
& & 3!

class Light {
// ...
// Only non-default Constructor
Light(int noOfWatts, boolean indicator, String location) { // (1)
this.noOfWatts = noOfWatts;
this.indicator = indicator;
this.location = location;
}
//...
}
class Greenhouse {
// ...
Light moreLight = new Light(100, true, "Greenhouse"); // (2) OK.
// Light firstLight = new Light(); // (3) Compile time error.
}

Overloaded Constructors
" #
'
& + Light & +
1! ) 4!
) & - Light
3! "& :! 9
& - "
# 53 4:3!

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


Page 22 of 57

class Light {
// ...
// Explicit Default Constructor
Light() { // (1)
noOfWatts = 50;
indicator = true;
location = "X";
}

// Non-default Constructor
Light(int noOfWatts, boolean indicator, String location) { // (2)
this.noOfWatts = noOfWatts;
this.indicator = indicator;
this.location = location;
}
//...
}

class Greenhouse {
// ...
Light moreLight = new Light(100, true, "Greenhouse"); // (3) OK.
Light firstLight = new Light(); // (4) OK.
}

4.5 Scope Rules


, +
+ # :@ 13A! &
6

J 6 & &

" 6 & & "

Class Scope for Members


! &
:1 & & )
:1 & 6

class SuperName {
int instanceVarInSuper;
static int staticVarInSuper;

void instanceMethodInSuper() { /* ... */ }


static void staticMethodInSuper() { /* ... */ }
// ...
}

class ClassName extends SuperName {


int instanceVar;

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


Page 23 of 57

static int staticVar;

void instanceMethod() { /* ... */ }


static void staticMethod() { /* ... */ }
// ...
}

) #
+ + - this super
* - " & &
) +

7 & &
+

& # :3 11:!
# 54 433!

# ?4 331!

# 54 433!

# 54 433!

* & J A

$ % & '
# ( ' & ' ) ' & ' ClassName
ClassName ' " & ' " &

' instanceVar 7
this.instanceVar
instanceVarInSuper
this.instanceVarInSuper
super.instanceVarInSuper

' instanceMethod() 7
this.instanceMethod()
instanceMethodInSuper()
this.instanceMethodInSuper()
super.instanceMethodInSuper()

# staticVar staticVar
this.staticVar
ClassName.staticVar ClassName.staticVar
staticVarInSuper staticVarInSuper
this.staticVarInSuper
super.staticVarInSuper
ClassName.staticVarInSuper ClassName.staticVarInSuper
SuperName.staticVarInSuper SuperName.staticVarInSuper

# staticMethod() staticMethod()

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


Page 24 of 57

this.staticMethod()
ClassName.staticMethod() ClassName.staticMethod()
staticMethodInSuper() staticMethodInSuper()
this.staticMethodInSuper()
super.staticMethodInSuper()
ClassName.staticMethodInSuper() ClassName.staticMethodInSuper()
SuperName.staticMethodInSuper() SuperName.staticMethodInSuper()

C C C
' /+ :5 duplicateLight 1!
Light oldLight newLight Light
- / private, &
oldLight newLight! duplicateLight() & 4! 3!
:!

' )

class Light {
// Instance variables
private int noOfWatts; // wattage
private boolean indicator; // on or off
private String location; // placement

// Instance methods
public void switchOn() { indicator = true; }
public void switchOff() { indicator = false; }
public boolean isOn() { return indicator; }

public static Light duplicateLight(Light oldLight) { // (1)


Light newLight = new Light();
newLight.noOfWatts = oldLight.noOfWatts; // (2)
newLight.indicator = oldLight.indicator; // (3)
newLight.location = oldLight.location; // (4)
return newLight;
}
}

Block Scope for Local Variables


" # {} "
" *
& " "
" & "'

&

* "2 & 1!
"1 % :4!

* +)

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


Page 25 of 57

* 8 " "8
" & 3! >! 5!

* " " " &


i 4! "3 :! ": &
" -

& " & "


index "4 / "4 "
1 index A! "1 '
" & index
"4

Review Questions

, D

# &

void method1 { /* ... */ }

void method2() { /* ... */ }

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


Page 26 of 57

void method3(void) { /* ... */ }

method4() { /* ... */ }

method5(void) { /* ... */ }

- ; & &
& D

public class ThisUsage {


int planets;
static int suns;
public void gaze() {
int i;
// ... insert statements here ...
}
}

# &

i = this.planets;

i = this.suns;

this = new ThisUsage();

this.i = 4;

this.suns = planets;

. ; & & D

void fly(int distance) {}


int fly(int time, int speed) { return time*speed; }
void fall(int time) {}
int fall(int distance) { return distance; }
void glide(int time) {}
void Glide(int time) {}

# & &

&
fly

&
fall

&
glide

&

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


Page 27 of 57

&

; Book &
D

# &

Book(Book b) {}

Book Book() {}

private final Book() {}

void Book() {}

public static void Book(String[] args) {}

abstract Book() {}

# & &

* private

* )

& & D

public class MyClass {


long var;
public void MyClass(long param) { var = param; } // (1)
public static void main(String[] args) {
MyClass a, b;
a = new MyClass(); // (2)
b = new MyClass(5); // (3)
}
}

# &

* & 1!

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


Page 28 of 57

* & 4!

* & 3!
& " int

&

4.6 Packages
* " ,
"

% :3 & + " " wizard


& " 6 pandorasBox spells " pandorasBox
Clown Magic " '
" pandorasBox LovePotion "
artifacts Ailment " spells & 6 Baldness
LovePotion Baldness Ailment " artifacts
" pandorasBox

/ + 0 &

.! $ " "
wizard.pandorasBox.LovePotion wizard.spells.LovePotion
Ailment wizard.pandorasBox.artifacts.Ailment
' " ' ,
$ "
! % + ( + LovePotion.class
wizard.pandorasBox.LovePotion &
wizard/pandorasBox

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


Page 29 of 57

* ' $
" ' " wizard & #
& sorcerersltd.com $ & 6

com.sorcerersltd.wizard

" wizard.pandorasBox.artifacts &


& $ # " %
" !
* " # :A *
# :@

Defining Packages
* " , '

$ / , !

, * ,
" package

package & +6

package ' # ;

* package
" , "

7 & $ %
& " #
"

' package ,
& # & &
& "

/+ :A 131 & " wizard.pandorasBox % :3


package

Using Packages
! "
" ; "
& & $ <& &
import

import package
import & +6

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


Page 30 of 57

import ' ;

* import
!
; & import 6

import wizard.pandorasBox.Clown;

Clown

* & import 6

import ' # .*;

' & "

* import "
"
!

* java.lang " # 101 3??!


& & String
$ java.lang.String

/+ :A & import < & & &


Baldness Baldness.java &
LovePotion " 6 wizard.pandorasBox wizard.spells
& & & $
<& " Baldness
$ " & #
import &
$

// File: Baldness.java
package wizard.spells; // (1)Package declaration
...
import wizard.pandorasBox.artifacts.*; // (3) Import from subpackage
...
public class Baldness extends Ailment { // (4) Abbreviated name for Ailment
wizard.pandorasBox.LovePotion tlcOne; // (5) Fully qualified name
LovePotion tlcTwo; // (6) Class in same package
...
}
}
...

Baldness + Ailment & " artifacts


wizard.pandorasBox " * & import 3!
" artifacts

& + & &

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


Page 31 of 57

& & import &


List java.awt.List + 6

import java.awt.*; // imports all class names from java.awt

; & & import 6

import java.awt.*; // imports all class names from java.awt


import java.util.*; // imports all class names from java.util

List & java.util.List java.awt.List

* java.awt.List + & List


6

import java.awt.*; // imports all class names from java.awt


import java.util.*; // imports all class names from java.util
import java.awt.List; // imports the class name List from java.awt

Compiling and Running Code from Packages


* "
" " . /+ :A "
wizard.pandorasBox wizard/pandorasBox javac
"
, ! Clown.java
LovePotion.java & wizard/pandorasBox
& package 6

package wizard.pandorasBox;

wizard/pandorasBox -d d
!& & javac *
/pgjc/work

>javac -d . Clown.java Ailment.java Baldness.java

work & ./wizard/pandorasBox


$ ! ,
! " .! -d
* /+ :A javac
/pgjc/work "
% :3 -d javac

($ $ D# /pgjc/work & &


Clown.class $ Clown java

>java wizard.pandorasBox.Clown

& Clown ./wizard/pandorasBox/Clown.class

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


Page 32 of 57

+ main()

, 4# H + & "
' CLASSPATH
& , &

The JAR Utility

,
*. , *. ! & ,
*,
*. jar * ,
*. &
+ ! '

& main()

jar " ( +tar ! *


" ,
*. + /+ :A! & +6

>jar cmf whereismain.txt bundledApp.jar wizard

9 c jar 9 m
' +
whereismain.txt! 9 f
bundledApp.jar! ,*. %
,
*. '
wizard & ' m f &
&

' ) ' /+ :A
+ main() wizard.pandorasBox.Clown
whereismain.txt & + 6

Main-Class: wizard.pandorasBox.Clown

Main-Class +
+ & &
jar

& 6

>java -jar bundledApp.jar

2 ,
*.

4.7 Accessibility Modifiers for Top-level Classes and


Interfaces
) & " public
& " '

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


Page 33 of 57

" "
" # "

* # A1 4?:

! ' 1

// File: Clown.java
package wizard.pandorasBox; // (1) Package declaration

import wizard.pandorasBox.artifacts.Ailment; // (2) Importing class

public class Clown implements Magic {


LovePotion tlc; // (3) Class in same package
wizard.pandorasBox.artifacts.Ailment problem;// (4) Fully qualified class name
Clown() {
tlc = new LovePotion("passion");
problem = new Ailment("flu"); // (5) Abbreviated class name
}
public void levitate() { System.out.println("Levitating"); }
public void mixPotion() { System.out.println("Mixing " + tlc); }
public void healAilment() { System.out.println("Healing " + problem); }

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


Clown joker = new Clown();
joker.levitate();
joker.mixPotion();
joker.healAilment();
}
}

interface Magic { void levitate(); } // (7)


_________________________________________________________________________________
// File: LovePotion.java
package wizard.pandorasBox; // (1) Package declaration

public class LovePotion { // (2) Accessible outside package


String potionName;
public LovePotion(String name) { potionName = name; }
public String toString() { return potionName; }
}
_________________________________________________________________________________
// File: Ailment.java
package wizard.pandorasBox.artifacts; // (1) Package declaration

public class Ailment { // (2) Accessible outside package


String ailmentName;
public Ailment(String name) { ailmentName = name; }
public String toString() { return ailmentName; }
}
_________________________________________________________________________________
// File: Baldness.java
package wizard.spells; // (1)Package declaration

import wizard.pandorasBox.*; // (2) Import of classes/interface


import wizard.pandorasBox.artifacts.*; // (3) Import from subpackage

public class Baldness extends Ailment { // (4) Abbreviated name for Ailment
wizard.pandorasBox.LovePotion tlcOne; // (5) Fully qualified name

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


Page 34 of 57

LovePotion tlcTwo; // (6) Class in same package


Baldness(String name) {
super(name);
tlcOne = new wizard.pandorasBox. // (7) Fully qualified name
LovePotion("romance");
tlcTwo = new LovePotion(); // (8) Class in same package
}
}

class LovePotion // implements Magic // (9) Not accessible


{ public void levitate(){} }

J & " & 6

>javac -d . Clown.java Ailment.java Baldness.java


>java wizard.pandorasBox.Clown
Levitating
Mixing passion
Healing flu

' /+ :A Clown Magic "


wizard.pandorasBox public Clown & Magic
& " wizard.pandorasBox '
" " "

LovePotion " wizard.pandorasBox


public " & Clown.java
LovePotion.java &
"

Clown Clown.java Ailment + & & &


& " 6

$ & :!
wizard.pandorasBox.artifacts.Ailment)

' + " wizard.pandorasBox.artifacts &


4! Ailment & >!

' Baldness.java @! LovePotion & Magic


" wizard.pandorasBox
" Magic
& " wizard.pandorasBox

,
C +
# :>

$ ) ' 1
$ ( 2 ' 1

! * " " !

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


Page 35 of 57

public * &

4.8 Other Modifiers for Classes


C abstract final )

abstract Classes

* & " & abstract *

* Vehicle abstract
& "
J )abstract " Car Bus & "
& "

* abstract # :10 1:A!


abstract 9 *
&
' & abstract
" abstract
* abstract
abstract

' /+ :? abstract Light abstract kwhPrice 1!


TubeLight
kwhPrice 4! Factory
TubeLight 3! . abstract &
:! abstract & >! . abstract
- & 5!

, '

abstract class Light {


// Fields
int noOfWatts; // wattage
boolean indicator; // on or off
String location; // placement

// Instance methods
public void switchOn() { indicator = true; }
public void switchOff() { indicator = false; }
public boolean isOn() { return indicator; }

// Abstract Instance Method


abstract public double kwhPrice(); // (1) No method body
}
class TubeLight extends Light {
// Fields
int tubeLength;

// Implementation of inherited abstract method.

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


Page 36 of 57

public double kwhPrice() { return 2.75; } // (2)


}

public class Factory {


public static void main(String[] args) {
TubeLight cellarLight = new TubeLight(); // (3) OK
Light nightLight; // (4) OK
// Light tableLight = new Light(); // (5) Compile time error
nightLight = cellarLight; // (6) OK
System.out.println("KWH price: " + nightLight.kwhPrice());
}
}

9 6

KWH price: 2.75

' - =
abstract !
& " & abstract

final Classes

* final + =
final
' & "
& 9 &
! final

* final & abstract J


final abstract ' &
abstract final * final & +
& * abstract &
& +

, *2' final = + java.lang.String &

' TubeLight /+ :? +
final6

final class TubeLight extends Light {


// Fields
int tubeLength;

// Implementation of inherited abstract method.


public double kwhPrice() { return 2.75; }
}

final # :10 1:5

$ ) 3& ' 1

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


Page 37 of 57

' 1
abstract J abstract '
final + ! 7

Review Questions

; & & &


" net.basemasterD

package net.basemaster;

public class Base {


// ...
}

# & &

Base

basemaster.Base

net.basemaster.Base

& net.basemaster.* Base

& net.* basemaster.Base

&
D

# &

class Ghost {
abstract void haunt();
}

abstract class Ghost {


void haunt();
}

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


Page 38 of 57

abstract class Ghost {


void haunt() {};
}

abstract Ghost {
abstract void haunt();
}

static class Ghost {


abstract haunt();
}

&
+ D

# &

class Link { }

abstract class Link { }

native class Link { }

static class Link { }

final class Link { }

private class Link { }

abstract final class Link { }

4.9 Member Accessibility Modifiers


&
! " &
+ &

* & 6

public

protected

# " !

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


Page 39 of 57

private

* " &

' & "


!
*
)
J A

' (C + + # - & public


protected private 7 + "

public Members

2 * public
& " " &

/+ :@ & & 1! 5! "


% :: & & " packageA packageB
J " packageB " packageA
SuperclassA packageA & 6 SubclassA packageA SubclassB packageB

-/

// Filename: SuperclassA.java (1)


package packageA;

public class SuperclassA {


public int superclassVarA; // (2)
public void superclassMethodA() {/*...*/} // (3)
}

class SubclassA extends SuperclassA {


void subclassMethodA() { superclassVarA = 10; } // (4) OK.
}

class AnyClassA {
SuperclassA obj = new SuperclassA();
void anyClassMethodA() {
obj.superclassMethodA(); // (5) OK.
}
}

_________________________________________________________________________________
// Filename: SubclassB.java (6)
package packageB;
import packageA.*;

public class SubclassB extends SuperclassA {


void subclassMethodB() { superclassMethodA(); } // (7) OK.
}

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


Page 40 of 57

class AnyClassB {
SuperclassA obj = new SuperclassA();
void anyClassMethodB() {
obj.superclassVarA = 20; // (8) OK.
}
}

* /+ :@ superclassVarA
superclassMethodA 4! 3! SuperclassA
/+ :@

J 16 % " & SubclassA


:!

J 46 % ) " & "


AnyClassA >!

J 36 % " & " SubclassB


A!

J :6 % ) " &
AnyClassB ?!

' /+ :@ superclassVarA superclass MethodA


#

2 % ::

protected Members

* "
" & ' & )
" " '

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


Page 41 of 57

' /+ :@ superclassVarA superclass MethodA


& " packageA
"

public class SuperclassA {


protected int superclassVarA; // (2)
protected void superclassMethodA() {/*...*/} // (3)
}

J : " packageB & % :>

* "
& & & SubclassB packageB
/+ :@ 6

// Filename: SubclassB.java
package packageB;
import packageA.*;

public class SubclassB extends SuperclassA { // In packageB.

SubclassB objRefB = new SubclassB(); // (1)

void subclassMethodB(SuperclassA objRefA) {


objRefB.superclassMethodA(); // (2) OK.
objRefB.superclassVarA = 5; // (3) OK.
objRefA.superclassMethodA(); // (4) Not OK.
objRefA.superclassVarA = 10; // (5) Not OK.
}
}

SubclassB SubclassB objRefB! subclassMethodB()


objRefA SuperclassA *
SuperclassA packageA & 4! 3!
& :! >! . superclassVarA
superclassMethodA() SubclassB
SuperclassA SubclassB SuperclassA &
objRefA < :! >!

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


Page 42 of 57

* &
SubclassB "

Default Accessibility for Members

I " / ! "

' /+ :@ superclassVarA superclass MethodA &


& " packageA
! "

public class SuperclassA {


int superclassVarA; // (2)
void superclassMethodA() {/*...*/} // (3)
}

" packageB J 3 :!
% :5

private Members

2
& "
#
& + -
# ?4 3:4! * "
*+

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


Page 43 of 57

' /+ :@ superclassVarA superclass MethodA

public class SuperclassA {


private int superclassVarA; // (2)
private void superclassMethodA() {/*...*/} // (3)
}

7 % :A

! / 2

$ )

public * &
protected * "
"
9 "
! " !
private 9 & &

Review Questions

! ; & &

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


Page 44 of 57

" com.corporation.projectD

package com.corporation.project;

public class MyClass {


int i;
public int j;
protected int k;
private int l;
}

# & &

% i "

% j "

% k "

% k "

% l "

% l "

, <& public protected


private D

# &

public

C public protected

C protected private

C private

protected & "


protected "

- D

# &

2 & & "

2 &

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


Page 45 of 57

* &
&

2 " K " &


default

4.10 Other Modifiers for Members


J K
& " & 6

static

final

abstract

synchronized

native

transient

volatile

static Members

+ " & static

# &

# " ! +
& ' &
-
+ + # ?4 335!

# " & *
' ) !

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


Page 46 of 57

- & <&
& I
&

* " & K -
' /+ :10 counter " "
Light + & writeCount
& 4! ) & 3!
counter & 0& main()
:! Warehouse & & Light
-

* & ) :1

. )

class Light {
// Fields
int noOfWatts; // wattage
boolean indicator; // on or off
String location; // placement

// Static variable
static int counter; // No. of Light objects created. (1)

// Explicit Default Constructor


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

// Static method
public static void writeCount() {
System.out.println("Number of lights: " + counter); // (2)
// Compile error. Field noOfWatts is not accessible:
// System.out.println("Number of Watts: " + noOfWatts); // (3)
}
}
public class Warehouse {
public static void main(String[] args) { // (4)

Light.writeCount(); // Invoked using class name


Light aLight = new Light(); // Create an object
System.out.println(
"Value of counter: " + Light.counter // Accessed via class name
);
Light bLight = new Light(); // Create another object
bLight.writeCount(); // Invoked using reference
Light cLight = new Light(); // Create another object
System.out.println(
"Value of counter: " + cLight.counter // Accessed via reference
);
}
}

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


Page 47 of 57

9 6

Number of lights: 0
Value of counter: 1
Number of lights: 2
Value of counter: 3

final Members

* final '

final

* final

* final
-

" & " # " %


! + Integer.MAX_VALUE &
+ int G final # 5:
4>1! 7 final
% final # 344 @:

* final !
# 54 433! #

% final
% # :?

final

' /+ :11 Light final 1! final 4!


* final 3! )
TubeLight final setWatts() Light
:! & Warehouse final aLight >!
- aLight 5!
A!

class Light {
// Final static variable (1)
final public static double KWH_PRICE = 3.25;

int noOfWatts;

// Final instance method (2)


final public void setWatts(int watt) {
noOfWatts = watt;
}

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


Page 48 of 57

public void setKWH() {


// KWH_PRICE = 4.10; // (3) Not OK. Cannot be changed.
}
}

class TubeLight extends Light {


// Final method in superclass cannot be overridden.
// This method will not compile.
/*
public void setWatts(int watt) { // (4) Attempt to override.
noOfWatts = 2*watt;
}
*/
}

public class Warehouse {


public static void main(String[] args) {

final Light aLight = new Light();// (5) Final local variable.


aLight.noOfWatts = 100; // (6) OK. Changing object state.
// aLight = new Light(); // (7) Not OK. Changing final reference.
}
}

abstract Methods

* abstract & +6

abstract " B LB L (B L)
B $ L;

* abstract =
abstract '
abstract ! + # :? 13:!
# abstract = &
abstract # # :? & /+ :? abstract

9 abstract #
& " * final abstract
! " & abstract &
C abstract
# 5: 4>1!

synchronized Methods

# + # @: 3>@!
+ - '
+ - synchronized
+ + *
+ synchronized -
synchronized

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


Page 49 of 57

' /+ :14 push() pop() synchronized StackImpl


7& + synchronized -
StackImpl - StackImpl
+ &
"

) & 5 &

class StackImpl {
private Object[] stackArray;
private int topOfStack;
// ...
synchronized public void push(Object elem) { // (1)
stackArray[++topOfStack] = elem;
}

synchronized public Object pop() { // (2)


Object obj = stackArray[topOfStack];
stackArray[topOfStack] = null;
topOfStack--;
return obj;
}

// Other methods, etc.


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

native Methods

7 ,
+ J JMM #
, # &
+ & " &
native ' " + throws & "
, + + & &

, 7 ' ,
7'! *2' & , "
J

' & + native Native 4!


" # ?4 335! 1! &
J Native native " 3!

class Native {

/*
* The static block ensures that the native method library
* is loaded before the native method is called.
*/
static {
System.loadLibrary("NativeMethodLib"); // (1) Load native library.
}

native void nativeMethod(); // (2) Native method prototype.


// ...

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


Page 50 of 57

class Client {
//...
public static void main(String[] args) {
Native aNative = new Native();
aNative.nativeMethod(); // (3) Native method call.
}
//...
}

transient Fields

9 - # -
- 9 - &
& &
# -

* transient
& - & ' & +
currentTemperature transient 1!
" & - <&
mass 4! " - Experiment
currentTemperature & mass
& -

class Experiment implements Serializable {


// ...
// The value of currentTemperature will not persist
transient int currentTemperature; // (1) Transient value.
double mass; // (2) Persistent value.
}

# transient
# -

volatile Fields

+ #
&
& & volatile
&
&

' + & clockReading


+ & " &
clockReading volatile &
& & & &

class VitalControl {
// ...
volatile long clockReading;
// Two successive reads might give different results.

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


Page 51 of 57

$ ) 3&
&
static
final
abstract 7 7 '
abstract
synchronized 7 9 +

native 7

transient & 7
& -
volatile & 7

Review Questions

. D

# & &

' public protected private!


"
&

E &
" &

# " +

static

9 - -

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


Page 52 of 57

; & & &


D

abstract class MyClass {


abstract void f();
final void g() {}
// final void h() {} // (1)

protected static int i;


private int j;
}

final class MyOtherClass extends MyClass {


// MyOtherClass(int n) { m = n; } // (2)

public static void main(String[] args) {


MyClass mc = new MyOtherClass();
}

void f() {}
void h() {}
// void k() { i++; } // (3)
// void l() { j++; } // (4)

int m;
}

# &

final void h() {} // (1)

MyOtherClass(int n) { m = n; } // (2)

void k() { i++; } // (3)

void l() { j++; } // (4)

& & D

class MyClass {
static MyClass ref;
String[] arguments;

public static void main(String[] args) {


ref = new MyClass();
ref.func(args);
}

public void func(String[] args) {


ref.arguments = args;
}
}

# &

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


Page 53 of 57

& main()
) func()

& ) func()
ref

& args
main() ) func()

& func()
ref ) arguments

& & & + &

&

; & & D

int a; // (1)
static int a; // (2)
int f() { return a; } // (3)
static int f() { return a; } // (4)

# &

1! 3!

4! :!

1! :!

4! 3!

# &

* )
this " &

* ) )

/ - &

'

* this &

& & & D

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


Page 54 of 57

abstract class MyClass {


transient int j;
synchronized int k;

final void MyClass() {}

static void f() {}


}

# &

MyClass abstract

j transient

k synchronized

MyClass() final

f() static

7 & & = & &

& D

# &

static int a;

final Object[] fudge = { null };

abstract int t;

native void sneeze();

final static private double PI = 3.14159265358979323846;

! D

# & &

* final

% native

7 )abstract abstract

J native

* final

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


Page 55 of 57

, D

# &

&

J abstract

- & int[] a =
new int[10] & & a

* & abstract
abstract

Chapter Summary

& & 6

+ ) )

this

"

public! abstract final!

+ "

public protected private!


static final abstract synchronized native transient volatile!

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


Page 56 of 57

Programming Exercises

'
" + & " +

- & +
&
& & +
&

*& + /+ :1
+

+
$ &

" &
6

& &

" !

long
Account " com.megabankcorp.
records - " com.megabankcorp.
system

& &
&
& &
'
& " com.megabankcorp.system &
& &
&
& " com.megabankcorp.system

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


Page 57 of 57

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

Potrebbero piacerti anche