3. Nested / Inner Classes - Chillipower.com

whooshribbitSoftware and s/w Development

Dec 2, 2013 (3 years and 11 months ago)

102 views

SCJP 5.0 Study Guide:

Louis Botterill

31
-
03
-
2008



1.

Basics:

................................
................................
................................
................................
................................
................................
................................
........

1

2.

Enums

................................
................................
................................
................................
................................
................................
................................
.........

2

3.

Nested / Inner Classes:

................................
................................
................................
................................
................................
................................
................

2

4.

Boxing:

................................
................................
................................
................................
................................
................................
................................
.......

2

5.

Asserts

................................
................................
................................
................................
................................
................................
................................
........

3

6.

File I/O

................................
................................
................................
................................
................................
................................
................................
.......

3

7.

Serialization

................................
................................
................................
................................
................................
................................
................................

3

8.

Dates, Numbers and Currency

................................
................................
................................
................................
................................
................................
....

4

9.

Regex

................................
................................
................................
................................
................................
................................
................................
..........

4

10.

Collections:

................................
................................
................................
................................
................................
................................
................................
.

5

11.

Sorting

................................
................................
................................
................................
................................
................................
................................
........

7

12.

Generics

................................
................................
................................
................................
................................
................................
................................
......

8

13.

Threads

................................
................................
................................
................................
................................
................................
................................
.......

8

14.

Development
................................
................................
................................
................................
................................
................................
...............................

9


1.

Basics:


Identifiers, begin with letter, underscore or $, after than

they can contain numbers too.

Java beans: getX, setX, isX, add, remove.


Types:


Object, has important methods such as:


boolean equals(Object obj)

// polymorphic, override this


equals must compare like type objects

void finalize()

// called only ever o
nce, before gc (and it’s implementation can prevent gc from happening!)

int hashCode()

// should implement for objects as hash keys, worst case it can return a constant value

final

void notify()

// notify one (first) waiting thread

final

void notifyAll()

// notify all waiting threads

final

void wait()

// wait on object lock via notify

String toString()


Scope:


public
-

all

protected


same package + inherited

default


same package

private


none!


class, public or default scope only

class, 0
-
1 public cla
ss matching file name, any number of non
-
public (default) classes


no file name restrictions

single abstract method means whole class must be marked as abstract


interface constants are always public static final (but these can be omitted (or included in
any order) as this is the only option!)

interfaces can
extend

other interfaces (note, never implement!)


Constructors:


Default no
-
arg constructor provided if you don’t provide any constructors.

Constructors only directly invoked by other constructors (or
by new keyword).

Can’t call super and this in the same constructor.

First statement must be a call to either this() [an overloaded constructor] or super(), compiler always adds call to super()
as 1
st

line unless you specify it.

Instance variables only avai
lable after call to super returns (super is 1
st

line).

Never inherited, therefore never overridden


only ever overloaded.

A private constructor means no default arg constructor can be invoked; even a subclass that attempts to call this (implicitly

or expl
icitly) will fail! i.e. can’t create object
unless other constructors are provided and invoked explicitly.


Special keywords:


transient



applied to instance variables only, means skip the variable when serialising the object.

volatile



applied to a vari
able only, means the value may change



Overloading:


Covariant returns in java 5.0 (e.g. return values can be subtypes (pass an is
-
a test))

Can’t reduce the access modifier

Can’t throw new or wider exceptions (can ‘not declare’ an exception (narrower scop
e!))


Overriding:



Signature matching



Conversions:


try

{


int

i1 = Integer.
parseInt
("123");




Integer

i2 = Integer.
valueOf
("123");



//Long l = Integer.valueOf("123"); // can't do this! Integer is not a Long

}

catch (NumberFormatExc
eption ex)

{


ex.printStackTrace();

}


int

i3 = (new Integer(123)).
intValue
();



2.

Enums


Can be top level or within a class (
but not a method!
)


enum MyEnums

{


bread(1),


cheese(2),


milk(3), coal(6);




final int value;





MyEnums(int v)


{


value = v;


}




public int getValue()


{


return value;


}

}


3.

Nested / Inner Classes:

4 types (1 nested and 3 inner):


Inner class:

Declared inside another class

Can be marked with access modifies a
nd abstract or final

Shares relationship with enclosing class instance, has access to all outer classes members (including private!)

From within the outer class, can instantiate normally as per MyInner mi = new MyInner();

From outside the outer class, can
instantiate using: MyOuter mo = ne
w MyOuter(); MyInner mi = new mo
.MyInner();

In inner class,
this

refers to inner class instance, can reference outer class instance using MyOuter.this;


Method
-
Local Inner class:

Declared in a method

Can only be abstract o
r final (not public, private etc)

Must be instantiated


within the same method,
after

it is declared

Can not use variables declared within method or parameters unless they are
final


Anonymous Inner class:

A class with no name declared in a statement that

either subclasses a named class or implements an interface

The only methods that can be called on an anonymous inner class are those belonging to the reference variable’s type (e.g. su
perclass or interface)

Extends one class or implements one interface (c
an’t do more than one thing)


Static nested Classes:

Inner classes marked with static keyword

It’s a top level nested class, not an inner class

Does not share any relationship with outer class. Don’t need instance of outer class to create it.

User Outer.In
ner syntax to instantiate, e.g. MyOuter.MyNested mn = new MyOuter.MyNested();

Can not access non
-
static members of outer class, can not get outer
this

reference as you can with Inner classes


4.

Boxing:


* Can implicitly convert from primitive to wrapper


wa
tch out!


Wrappers can not be cast to other wrappers (i.e. do not pass an “is a” test)


Integer is
-
not
-
a Short


i.e. can’t do


Short short1 = new Short(100);


Cannot find symbol : constructor Short(int) or Short(Integer)


But this is fine


Short short
1 = new Short((short)100);

Or

Long long1 = (Long)
(long)
myShortObj;

// involves unboxing, conversion, reboxing…



5.

Asserts


assert
Expression
1

;


assert if assertion enabled and expression1 evaluates to false


assert
Expression
1

:
Expression
2

;


as above
but evaluate expression2 (not void!) as the message detail for the assertion


An assertion error is a
java.lang.AssertionError
, a type of
java.lang.Error

which in turn is a type of
java.lang.Throwable


Must be source level 1.4 or higher


Enable assertions
with
-
enableassertions
, or

ea

-

disable with

disableassertions

or
-
da


Enable for specific packages / classes


java
-
ea:com.wombat.fruitbat...
-
da:com.wombat.fruitbat.Brickbat BatTutor

source mode 1.3

(default)


the compiler accepts programs that use
a
ssert

as an identifier, but issues warnings. In this mode, programs are
not

permitted to use the
assert

statement.

source mode 1.4



the compiler generates an error message if the program uses
assert

as an identifier. In this mode, programs
are

permitted t
o use the
assert

statement.

6.

File I/O


Main classes:


File



abstract representation of file and path names (not an actual file!)




File(String pathAndFileName), File(path, filename), file.exists(), file.createNewFile(), file.delete(), file.isDirectory()
, file.list(), file.mkdir(), file.renameTo()


FileReader



read characters from a file


FileReader(File), fileReader.read()

BufferedReader



Buffers up date, provides higher level methods like readLine(), construct like new BufferedReader(new FileReader(f
ile))

FileWriter



as per FileReader


fileWriter.write(“some lovely string”); fileWriter.flush(), fileWriter.close();

BufferedWriter


PrintWriter



Enhanced in Java5


constructors to build from file or string. Has
format(), printf(), append()


NB: Always

remember IOExceptions can be thrown!


NB: New File does not create the file but a new FileWriter, PrintWriter or FileOutputStream on a File will create it


except if the directory doesn’t exist
-
>
IOException: No such file or directory


NB: Streams read
and write bytes, Readers and writers read and write characters. All file I/O exam questions are about characters, streams are

used elsewhere


e.g.
serialization.


7.

Serialization


Main classes:


java.io.DataInputStream

java.io.DataOutputStream

java.io.FileI
mputStream

java.io.FileOutputStream

java.io.ObjectInputStream

java.io.ObjectOutputStream



ObjectOutputStream.writeObject(obj)

Type obj = (type)ObjectInputStream.readObject();


Classes must implement serializable


Use transient to mark a variable as not to

be included in default serialisation, for example if it’s not marked as serializable and can not be modified (final or in a l
ibrary)


Then override writeObject and readObject to perform your own serialisation for transients


public void writeObject(Object
OutputStream os)

{


try


{



os.defaultWriteObject();



os.writeInt(myTransient.getInt());


}


catch (Exception e) {}

}


public void readObject(ObjectInputStream is)

{


try

{

is.defaultReadObject();



myTransient = new MyTransient(os.readInt());

}


catch (
Exception e) {}

}



defaultReadObject and defaultWriteObject are default implementations available when an object is marked as serializable


NB. If a superclass is marked serializable, all subclasses are serializable whether marked explicitly or not (all p
ass an is
-
a test), but unless you can see all the code it’s
hard to know.


NB. Classes marked as serializable do not run their constructor when being deserialized. However, if a superclass is not seri
alizable and a subclass is, the superclasses
contructor
(and all subsequent constructors) will be run, the serializable subclass will still _not_ have its constructor called.


NB: serialisation is not for statics!


8.

Dates, Numbers and Currency


Own Locale:


Date d = new Date();

Date.toString(); // date and time

(your locale)


Calendar c = Calendar.getInstance();

c.add(), c.roll() …


Locales:


Locale loc = new Locale();

Locale loc = new Locale(language);

Locale loc = new Locale(language, country);


Calendar c = Calendar.getInstance(loc);


Formatting dates in diff
erent locales:


DateFormat.getInstance(); // Get a default date/time formatter that uses the SHORT style for both the date and
the time.

DateFormat.getDateInstance();

// Gets the date formatter with the default formatting style for the default
locale.

Date
Format.getDateInstance(style);

DateFormat df = DateFormat.getDateInstance(style, loc); // style


DateFormat.SHORT, DateFormat.MEDIUM,
DateFormat.LONG, DateFormat.FULL


String dateString = df.format(date);


Format numbers / currency:


Locale loc = new Loca
le(…);

NumberFormat nf = NumberFormat.getInstance(loc);


Or


NumberFormat nf = NumberFormat.getCurrencyInstance(loc);


String s = nf.format(some number);



9.

Regex


NB: all regex
\

metacharacters must be escaped as
\
\

in Java strings!


Example code:

java.uti
l.regex.*


Pattern p = new Pattern(“ab”); the regex expression

Matcher m = p.matcher(“alsdjajslda”); // the source to match on


while (m.find())

{


System.out.println(m.start() + “ ” + s.group());

}


start = start index of match (0 based), group = the m
atched group of characters


Meta
-
characters:


char

type

E
xample


\
d

digit


y
d” “A12b”
=
ptart猠1=O
=
y
s
=
white獰ace
=

y
s” “a bc d”
=
ptart猠1=4
=
y
w
=
word=(letterI=digitI=_)
=

y
w” “1 e 3f”
=
ptart猠M=O=45
=
[abc]

Char match in range abc

“[abc]” “adc”

Starts 0 2

[a
-
f]

Char match a through f inc.

“[a
-
f]” “gfc”

Starts 1 2

[a
-
fA
-
F]

a through f and A through F



+

One or more


\
d+” “1 a12 b234”

Groups 1 12 234

*

Zero or more



?

Zero or one



.

Any character

“a.c” “ac abc a c”

3 abc, 7 a c

^

Negate the character

[^a
bc] = not ab or c








Example: find hex characters of the form 0x1ab2Ef or 0X2Efga etc


0[xX]([0
-
9a
-
fA
-
F])+


means find (0 x or X
) and then (0
-
9 or a
-
f or A
-
F) 1 or more

times


NB:

Greedy (default for ? * and +) means search right to the end then work

backwards…


e.g.


source yyxxxyxx

pattern .*xx (any char zero or more times followed by xx)


searches and matches on the LAST xx not the first XX and
greedily

returns yyxxxyxx


The dot . means any character, to actually specify a literal dot, we escape it

to be
\
. (in a Java string literal that needs to be
\
\
.)


String has a .split(regexpattern) method that produces a String[] array of the matched patterns.


Tokenising
-

Scanner


e.g. new Scanner(“some message to tokenise”);


Has methods like:


hasNext()


test for next token (of any type)

nextInt()


returns all tokens as string and move forward


boolean hasNextInt()


test for next int token

int nextInt()


get next int token and move forward


can also find tokens using regex


token = s.findInLine(“some r
egex expr”)


NB: Default scanner tokenising character is whitespace.


Printf


System.out.printf uses the following format string construction


%[arg_index$][flags][width][.precision]conversion char


Flags:


"
-
" Left justify this argument

"+" Include a sign

(+ or
-
) with this argument

"0" Pad this argument with zeroes

"," Use locale
-
specific grouping separators (i.e., the comma in 123,456)

"(" Enclose negative numbers in parentheses




Conversion codes:


b
boolean

c
char

d
integer

f
floating point

s
string


10.

Collections:


Code to interfaces where possible, e.g. where the type on the right passes an “is a” test for the thing on the left:


List<Integer> = new ArrayList<Integer>();


Java.util.Arrays has various sort methods


Java.util.Collections has sort methods


To use objects as keys in hash maps (HashSet, LinkedHashSet, HashMap, Hashtable, LinkedHashMap)


Override equals to provide a meaningful comparison of objects. Override hash code so that hash codes are typically different
for different objects but always

the same
for objects that are equal.


Iterating


can use enhanced for loop or iterators


hasNext (check if there is a next) and next (get next item)





Main Classes:


Class java.util.
Arrays:


Main methods:


static list
asList
(T[]);

static int
binarySearch
(Object[], key);

static int
binarySearch
(primitive[], key);

static int
binarySearch
(T[], key, comparator);

static Boolean
equals
(Object[], Object[]);

static Boolean
equals
(primitive[], primitive[]);

static void
sort
(Object[]);

static void
sort
(primitive[]);

static void
sort
(T[], Comparator);



Class java.util.
Collections
:


static <T> int
binarySearch
(
List
<? extends
Comparable
<? super T>>

list, T

key)

static <T> int
binarySearch
(
List
<? extends T>

list, T

key,
Comparator
<? super T>

c)


static <t> Comparator<T>
reverseOrder
()


Returns a comparator that imposes the reverse of the
natural ordering

on a collection of objects that implement the
Comparable

interface.


static <t> Comparator<T>
reverseOrder
(
Comparat
or
<T>

cmp)


Returns a comparator that imposes the reverse ordering of the specified comparator.


static <T extends Comparable<? Super T>> void
sort
(
List
<T>

list)


Sorts the specified list into ascending order, according to the
natural ordering

of its elements.


Collection

<interface>

Set

<i
nterface>

List

<interface>

Queue

<interface>

HashSet

<class>

SortedSet

<interface>

TreeSet

<class>

LinkedHashSet

<class>

ArrayList

<class>

Vector

<class>

LinkedList

<class>

PriorityQueue

<class>

Object

<class>

Arrays

<class>

Collections

<class
>

Map

<interface>

SortedMap

<interface>

Hashtable

<class>

HashMap

<class>

TreeMap

<class>

LinkedHashMap

<class>

static <T> void
sort
(
List
<T>

list,
Comparator
<? super T>

c)



Sorts the specified list according to the order induced by the specified comparator.


Remember, must always sort before searching!


Interfaces:


Collection



defines: add, addAll, clear, contains, isEmpty, iterator, remove, removeAll, size, toArray etc

Implements
-

Iterable

Implemented By


BlockingQueue, List, Queue, Set, SortedSet etc


List



defines: add, get, set, remove, indexOf,

remove all, toArray, size etc

Implements
-


Implemented by
-

ArrayList, LinkedList, Stack, Vector etc


Queue



defines: element, offer, peek, poll, remove

Implements
-

Collection, Iterable

Implemented By
-

AbstractQueue, ArrayBlockingQueue, ConcurrentLi
nkedQueue, DelayQueue, LinkedBlockingQueue, LinkedList, PriorityBlockingQueue,
PriorityQueue, SynchronuousQueue


Set



defines: add, addAll, clear, contains, remove, removeAll, size, toArray etc

Implements


Collection, Iterable

Implemented By


HashSet,
LinkedHashSet, TreeSet etc


Map



defines: clear, containsKey, containsValue, get
(Object key)
, keySet, put
(Object key, Object value)
, putAll, remove, size, values etc

Implements


Implemented By


HashMap, Hashtable, LinkedHashMap, TreeMap etc


SortedSet



defines: comparator, first, headset, last, subset, tailSet

Implements


Collection, Iterable

Implemented By
-

TreeSet


NB: Map interface does not extend the Collection interface



General
-
Purpose Implementations

-

The primary implementations of the collec
tion interfaces.


HashSet

-

Hash table implementation of the
Set

interface. The best all
-
around implementation of the
Set

interface.

TreeSet

Red
-
black tree implementation of the
SortedSet

interface.

LinkedHashSet

-

Hash table and linked list implementation of the
Se
t

interface. An
insertion
-
ordered
Set

implementation that runs nearly as fast as
HashSet
.

ArrayList

-

Resizable
-
array implementation of the
List

interface. (Essentially an un
synchronized
Vector
.) The best all
-
around implementation of the
List

interface.

LinkedList

-

Doubly
-
linked list implementation of the
List

interface. May provide better perf
ormance than the
ArrayList

implementation if elements are
frequently inserted or deleted within the list. Can be used as a double
-
ended queue (deque). Also implements the
Queue

interface. When accessed via the
Queue

interface,
LinkedList

behaves as a
FIFO
queue
.

PriorityQueue

-

Heap implementation of an unbounded priority queue.

HashMap

-

Hash
table implementation of the
Map

interface. (Essentially an unsynchronized
Hashtable

that supports
null

keys and values.) The best all
-
around
implementation of the
Map

interface.

TreeMap

Red
-
black tree implementation of the
SortedMap

interface.

LinkedHashMap

-

Hash table and linked list implementation of the
Map

interface. An insertion
-
ordered
M
ap

implementation that runs nearly as fast as
HashMap
.
Also useful for building caches (see
removeEldestEntry(Map.Entry)

).



NB: TreeSet and TreeMap implement the SortedSet interface and provide sorted insertion (default or supplied comparator). If y
ou add an object that doesn’t provide
compareTo you will get a ClassCastException at runtime!


Map (Interface)

Object get(Object

key)

Object put(Object key, Object value)

boolean containsKey(Object key)

int size()


11.

Sorting


NB:

To be searched, an array or List must first be sorted. To be sorted (and thus searched) a List’s elements must be
comparable


Define sorting/comparison for
a type using
:


x implements Comparible<T>

{


public int
compareTo
(T t)


{




}

}


e.g.

Collections.sort(List, Comparator)


Comparator

is an interface, used to provide a custom comparison implementation for sorting:


x implements
Comparator

{

publ
ic int
compare
(Object o1, Object o2)

}


or


x implements
Comparator
<t>

{

public int
compare
(T t1, T t2) {…}

}



java.util.Collections and java.util.Arrays both provide:


a sort() method which can sort in natural order or use overloaded method that takes
a comparator.

A binarySearch method to search a pre
-
sorted array or List


Collections.reverse()

reverses the order of the elements in a List

Collections.reverseOrder()

provides a comparator that sorts in reverse


Lists and Sets have toArray to create array
s


12.

Generics

Although with arrays (no generics) you can do


Object[] list = new JButton[4];


For generics we can do:



List<T1> = new ArrayList<T1>();


But T1 must match, you can not do anything that looks like the array declaration above, like:


List<Obje
ct> = new ArrayList<MyObject>(); // can’t do this!


ArrayList<T> can contain any T, or subclass of T


Mixing new generic and older non generic code can cause compile time
warnings

(at run time the two are the same anyway) but the code will compile and run


it may
cause run time exceptions if wrong types are added/expected etc (class cast exceptions etc)


e.g. pass generic List<String> into a non
-
generic method void foo(List aList) will create a compiler warning


“potentially unsafe operation”
.



void add(
List<Dog> d)

can take a List of type Dog
ONLY


void add(List<? Extends Dog>

can take anything is
-
a Dog, Dog and subclasses of Dog


When using
wildcard

syntax, the collection can be accessed but
not modified


List<?>

means any type (any type extends object
)


is the same as
List<? extends object>


Conventions:


T

is for type e.g. List<E>

E

is for element e.g. add(E e)


NB:
Arrays of generic types are only allowed, if the values of the type variable is the unbounded wildcard.



13.

Threads


Thread


void run()

vo
id start()

void stop()

static void yield()

static void sleep(long ms) throws InterruptedException

final static void join() throws InterruptedException

final static void setPriority(int priority)



+ from object


final void wait() InterruptedException

final

void notify()

final void notifyAll()



States



New, Runnable, Running, Waiting/blocked/sleeping, dead


Priorities:


Thread.MIN_PRIORITY (1)

Thread.NORM_PRIORITY (5)

Thread.MAX_PRIORITY (10)



Two ways to make a thread, extends Thread or implements Runnab
le


Chass MyThread
extends Thread



MyThead t = new MyThread();


Or


MyRunnable class implements Runnable


MyRunnable r = new MyRunnable();


Thread t = new Thread(r);



Synchronisation:


synchronized


methods, on blocks



Thread goes to sleep holding its

lock


Thread can acquire more than one lock


Thread tries to get lock, thread becomes blocked on object lock


Static and non
-
static synchronized methods (or blocks on instance and class.class) will not block each other.



wait, notify and notifyAll


A cal
l to an objects wait/notify must be within synchronized code on the object in question! Or you will get a compilation error a
long the lines of:


java.lang.IllegalMonitorStateException: current thread not owner


i.e. a thread can’t invoke wait/notify withou
t owning the objects lock first!


wait releases the lock (gained when entering the synchronized method/block) and waits to gain it again, in the blocked/waitin
g state waiting for the other thread to call
notify/notifyAll


When wait is called, the lock is r
eleased immediately, however when notify is called the lock isn’t given up until it moves out of the synchronized code that c
ontains it



14.

Development


javac


-
d option, directory for classes


NB: this will throw an error if the specified directory does not

exist. Directories below the directory given will contain the compiled classes, as defined in their package
structure.



java


-
da disable assertions

-
ea enable assertions

-
D property value e.g.

DmyProperty=Value or

DmyProperty=”some value with spaces”


java.util.Properties


Properties p = System.getProperties();

p.setProperties(“myProperty”, “myValue”);

p.list(System.out);


main()


static void main method can use var args, the following signatures are all valid for main:


static public void main(String[
] args);

public static void main(String… stringVarArgsArray);

static public void main(String stringArray[])



classpaths:


-
classpath,
-
cp e.g.

classpath .:

/com:/stuff


when searching, the first found match is used (stops looking once a match is found).


Search order

1. Java platform classes

2. Directories specified in the classpath


Declare classpaths in operating system environment or on the command line.


NB: only the final directory of a classpath path is searched, e.g. /my/lovely/path would _only_ se
arch the path directory.


Jar files:


Include in the classpath by specifying the jar file explicitly


such as:
javac

classpath folder/myApp.jar Stuff.java


Static imports (import static):


Can import methods and variables of a class into the current name
space: e.g.


import static java.lang.System.out

import static java.lang.Integer.*;


would give access to out.println and MAX_VALUE (public static const from the Integer class) directly.


NB: static import is a syntax error!