Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
! "
public final static abstract! #
" $
% &
'
Supplementary Objectives
( this
( &
' ) &
4.1 Arrays
* + +
*
) *
+ +
' , - * '
'
. -
/ - final length &
# $ #
- - - &
2 # 340
# 55
[] ;
[];
&
[] 7
' '
-
[] & 9 & []
&
*
& null
#
4: 33! &
Constructing an Array
* new
= new [ ! ];
! 0 &
, ! ' NegativeArraySizeException &
; & 6
&6
1
[] = new 2
[ ! ];
<& 2
[] " 1
[] # 55 450!
2 &
' + &
% + +2 anIntArray
0 +3 mediumPizzas null &
length
= + medium Pizzas.length 5
9 + =
+ /+ "
Initializing an Array
, +
6
[] = { ! };
& !
) + # "
objArray Object
& & Pizza
- & null 7 -
6 - &
& Pizza -
+ !
+ ' +
! " } "
& & 6
1! & String -
& 4! " String -
char
// Array of 3 characters
char[] charArray = {'a', 'h', 'a'}; // (2) Not the same as "aha".
Using an Array
&
+& [] + &
+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]);
}
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[] 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)
}
9 6
Minimum value: 2
Multidimensional Arrays
# - -
' , &6
[][]...[] ;
[][]...[];
' $ $ " []
+ *
& $ 6
' &
mXnArray &
&! 5 int &
4) & <&
,
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[]
[][][] % $ "
:) &
double[][] matrix2 = {
{0.0}, // 1. row
{0.0, 0.0}, // 2. row
{0.0, 0.0, 0.0} // 3. row
}
7 ' /+ :3
:+3int + 1!
+ 4! & mXnArray[i] 0 iB
mXnArray.length! 3! & mXnArray
class MultiArrays {
9 6
Minimum value: 5
Review Questions
; & & +
D
int[] array;
# &
array[].length()
array.length()
array[].length
array.length
array[].size()
array.size()
' D
# &
E &
E -
7 ) main()
) String &
7 ,
& D
# &
# & &
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 ];
# &
& int[]
; & & 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");
}
}
}
# &
&
! & & D
# &
&
& F
0 false NaN nullF
& F
0 false 0 nullF
& F
null 0 0 nullF
& F
null false 0 nullF
class
// Class header
{ // Class body
! " #
}
" # :A 131!
# :? 13:!
# 51 445!
# 5: 4>1!
" &
# 43 31!
# :3 114!
# A1 4?:!
C static " )
- " '
& 6
# :: 11A!
! " # # ?4 331!
"
( )
$ // Method prototype
{ // Method body
"
' &
6
# :10 1::!
void #
>: 1A5!
)
& " # 31A ?5! *
( ) /
6
# :> 143!
final # 344 @:
" #
% " # 43 31
# A: 304
" 6
&
Statements
# , G & +
# 43 31 #
:1 104! 9 $ # >1 1>?!
* + +
9 +
& 6
# 3: :A!
# 3A 53!
# 31A ?5!
* " {} &
# :> 143! " "
* " +&
& " {
& } # " &
" # :1 104!
# >: 1A1
' - " - *
) +
this - &
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;
9 6
Light@df6ccd
Light@df6ccd
No. of watts: 100
Indicator: false
Location: null
' -
this >! /+ :: & -
println()
7 this + +
+ -
Method Overloading
/ &
#
#
. & &
$ , 4# H *2' "
% + java.lang.Math min() &
&
&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!
- C & &
*
# 54
43A 9
C &
# 54 433!
4.4 Constructors
- & -
new
* & +6
" ( )
$ // Constructor header
{ // Constructor body
"
C
* # :A 131
J void
return
J +
/+ :> & 4!
1! < &
Name() { // (1)
System.out.println("Constructor");
}
9 6
Constructor
Method
Default Constructor
* & ' & &
6
()
'
$ & 6
"
- # 53 4:3! '
-
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() { super(); }
* ' &
+ 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.
}
' +
- ' $
' + & 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!
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.
}
J 6 & &
class SuperName {
int instanceVarInSuper;
static int staticVarInSuper;
) #
+ + - 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()
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; }
&
* "2 & 1!
"1 % :4!
* +)
* 8 " "8
" & 3! >! 5!
Review Questions
, D
# &
method4() { /* ... */ }
method5(void) { /* ... */ }
- ; & &
& D
# &
i = this.planets;
i = this.suns;
this.i = 4;
this.suns = planets;
. ; & & D
# & &
&
fly
&
fall
&
glide
&
&
; Book &
D
# &
Book(Book b) {}
Book Book() {}
void Book() {}
abstract Book() {}
# & &
* private
* )
& & D
# &
* & 1!
* & 4!
* & 3!
& " int
&
4.6 Packages
* " ,
"
/ + 0 &
.! $ " "
wizard.pandorasBox.LovePotion wizard.spells.LovePotion
Ailment wizard.pandorasBox.artifacts.Ailment
' " ' ,
$ "
! % + ( + LovePotion.class
wizard.pandorasBox.LovePotion &
wizard/pandorasBox
* ' $
" ' " wizard & #
& sorcerersltd.com $ & 6
com.sorcerersltd.wizard
Defining Packages
* " , '
$ / , !
, * ,
" package
package & +6
package ' # ;
* package
" , "
7 & $ %
& " #
"
' package ,
& # & &
& "
Using Packages
! "
" ; "
& & $ <& &
import
import package
import & +6
import ' ;
* import
!
; & import 6
import wizard.pandorasBox.Clown;
Clown
* & import 6
* 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
...
}
}
...
package wizard.pandorasBox;
wizard/pandorasBox -d d
!& & javac *
/pgjc/work
>java wizard.pandorasBox.Clown
+ main()
, 4# H + & "
' CLASSPATH
& , &
,
*. , *. ! & ,
*,
*. jar * ,
*. &
+ ! '
& main()
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
2 ,
*.
" "
" # "
* # A1 4?:
! ' 1
// File: Clown.java
package wizard.pandorasBox; // (1) Package declaration
public class Baldness extends Ailment { // (4) Abbreviated name for Ailment
wizard.pandorasBox.LovePotion tlcOne; // (5) Fully qualified name
$ & :!
wizard.pandorasBox.artifacts.Ailment)
,
C +
# :>
$ ) ' 1
$ ( 2 ' 1
! * " " !
public * &
abstract Classes
* Vehicle abstract
& "
J )abstract " Car Bus & "
& "
, '
// Instance methods
public void switchOn() { indicator = true; }
public void switchOff() { indicator = false; }
public boolean isOn() { return indicator; }
9 6
' - =
abstract !
& " & abstract
final Classes
* final + =
final
' & "
& 9 &
! final
' TubeLight /+ :? +
final6
$ ) 3& ' 1
' 1
abstract J abstract '
final + ! 7
Review Questions
package net.basemaster;
# & &
Base
basemaster.Base
net.basemaster.Base
&
D
# &
class Ghost {
abstract void haunt();
}
abstract Ghost {
abstract void haunt();
}
&
+ D
# &
class Link { }
* & 6
public
protected
# " !
private
* " &
public Members
2 * public
& " " &
-/
class AnyClassA {
SuperclassA obj = new SuperclassA();
void anyClassMethodA() {
obj.superclassMethodA(); // (5) OK.
}
}
_________________________________________________________________________________
// Filename: SubclassB.java (6)
package packageB;
import packageA.*;
class AnyClassB {
SuperclassA obj = new SuperclassA();
void anyClassMethodB() {
obj.superclassVarA = 20; // (8) OK.
}
}
* /+ :@ superclassVarA
superclassMethodA 4! 3! SuperclassA
/+ :@
J :6 % ) " &
AnyClassB ?!
2 % ::
protected Members
* "
" & ' & )
" " '
* "
& & & SubclassB packageB
/+ :@ 6
// Filename: SubclassB.java
package packageB;
import packageA.*;
* &
SubclassB "
I " / ! "
" packageB J 3 :!
% :5
private Members
2
& "
#
& + -
# ?4 3:4! * "
*+
7 % :A
! / 2
$ )
public * &
protected * "
"
9 "
! " !
private 9 & &
Review Questions
! ; & &
" com.corporation.projectD
package com.corporation.project;
# & &
% i "
% j "
% k "
% k "
% l "
% l "
# &
public
C public protected
C protected private
C private
- D
# &
2 &
* &
&
static
final
abstract
synchronized
native
transient
volatile
static Members
# &
# " ! +
& ' &
-
+ + # ?4 335!
# " & *
' ) !
- & <&
& 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)
// 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)
9 6
Number of lights: 0
Value of counter: 1
Number of lights: 2
Value of counter: 3
final Members
* final '
final
* final
* final
-
* final !
# 54 433! #
% final
% # :?
final
class Light {
// Final static variable (1)
final public static double KWH_PRICE = 3.25;
int noOfWatts;
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
) & 5 &
class StackImpl {
private Object[] stackArray;
private int topOfStack;
// ...
synchronized public void push(Object elem) { // (1)
stackArray[++topOfStack] = elem;
}
native Methods
7 ,
+ J JMM #
, # &
+ & " &
native ' " + throws & "
, + + & &
, 7 ' ,
7'! *2' & , "
J
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.
}
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
& -
# transient
# -
volatile Fields
+ #
&
& & volatile
&
&
class VitalControl {
// ...
volatile long clockReading;
// Two successive reads might give different results.
$ ) 3&
&
static
final
abstract 7 7 '
abstract
synchronized 7 9 +
native 7
transient & 7
& -
volatile & 7
Review Questions
. D
# & &
E &
" &
# " +
static
9 - -
void f() {}
void h() {}
// void k() { i++; } // (3)
// void l() { j++; } // (4)
int m;
}
# &
MyOtherClass(int n) { m = n; } // (2)
& & D
class MyClass {
static MyClass ref;
String[] arguments;
# &
& 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 &
# &
MyClass abstract
j transient
k synchronized
MyClass() final
f() static
& D
# &
static int a;
abstract int t;
! D
# & &
* final
% native
7 )abstract abstract
J native
* final
, D
# &
&
J abstract
- & int[] a =
new int[10] & & a
* & abstract
abstract
Chapter Summary
& & 6
+ ) )
this
"
+ "
Programming Exercises
'
" + & " +
- & +
&
& & +
&
*& + /+ :1
+
+
$ &
" &
6
& &
" !
long
Account " com.megabankcorp.
records - " com.megabankcorp.
system
& &
&
& &
'
& " com.megabankcorp.system &
& &
&
& " com.megabankcorp.system