Transcript powerpoint

Nested and Inner classes
Reading for these lectures:
Weiss, Section 15.1 (Iterators and nested
classes),
Section 15.2 (Iterators and inner classes).
ProgramLive, Section 12.4
“Inside every large program there is a little
program just crying to get out.”
Sir Tony Hoare
.
1
8-queens solution
/** For each i, 0 <= i < b.length(), queen in row
i is in column b[i]. These are the only queens.
Add to solutions all solutions to the 8-queens
problem that have these b.length() queens. */
public static void generate(String b) {
if (b.length() == 8) {
solutions.add(b);
return;
}
/* invariant: All solutions with queen in row
b.length() placed in one of the columns
0..j-1 have been put into solutions. */
for (int j= 0; j < N; j= j+1) {
if (isLegal(b + j))
generate(b + j);
}
}
2
8-queens solution
/** Let m = b.length()-1. b is as in the spec of
generate, except that the queen in row m may
capture a queen in rows 0..m-1. Return “queen
m doesn’t capture queens in rows 0..m-1" */
public static boolean isLegal(String b) {
int m= b.length()-1;
int cm= b.charAt(m) - '0'; // column of queen m
/* Return “no queen in rows 0..m-1 can
be captured by the queen in row m” */
for (int i= 1; i <= m; i= i+1) {
int c= b.charAt(m-i) - '0'; // col for queen m-i
if (c == cm || c == cm-i || c == cm+i)
return false;
}
col cm-i. col cm. col cm+i.
return true;
}
row m-i
row m
3
Nested class
A nested class is a static class that is defined
inside another class. A nested class gets its
own file drawer.
A nested class can reference only static (and
not non-static) variables of the class in which
it is nested.
In method m,
can reference,
public class X {
public static final int Y= 2; p, q, Y,
but not x.
private int x;
private static class SC {
private int p;
private static int q;
public void m()
{ p= Y; q= p; }
}
A class that is
not defined
inside another
can’t be static
}
Reasons for using nested class. Get it out of
the way; perhaps make it private so others
can’t refer to it directly.
4
Questions about A3 that we get
Should we include < and > in the tags we
are supposed to return?
Answer on the handout:
/** = the next tag in the buffered reader, as
an instance of class String, including the
angle brackets < and > . …/
public Object next()
Do I have to use a constructor that contains
a BufferedReader as a parameter or can I
do something else?
Answer on the handout:
It should have a constructor withthis
specification:
/** Constructor: an enumeration of the
tags in br. Precondition: br != null
*/
public TagIterator(BufferedReader
br)
5
Questions about A3 that we get
Can a tag cover several lines?
Answer on the handout:
Notice that the format of attributes allows
several variations:
• There may be any amount of whitespace
on one or both sides of the "=". This
whitespace might include tabs and newline characters. …
Since attributes are in tags, tags can span several lines. As the examples in the table show
Can a comment include a tag?
Answer on handout:
Comments begin with "<!--" and end with
"-->":
<!-- this text is ignored -->
Everything before the closing "-->" is
ignored, even if the comment contains ">".
6
Questions about A3 that we get
Do the tags we return contain “\n”?
This one is NOT well answered in the
handout. Here is our answer.
Function br.readLine() of BufferedReader
throws away the ‘\n’ chars and does not include
them in its result. It is best if ‘\n’ chars do NOT
appear in the result, and we ask you not to
include them. If you already submitted your
assignment, don’t change it; we will take care
of it.
But for correctness, it may be best to insert a
blank char between lines. Please, insert either
nothing or a blank character BETWEEN lines.
Whichever you choose, do it consistently.
<a width=5
height=6>
become one of:
<a width=5height=6>
<a width=5 height=6>
7
Questions about A3 that we get
Should we parse the attributes and
enumerate one attribute tags only?
Answer in handout:
TagIterator does NOT have to deal with the
contents of tags --the different kinds of
attributes. All it is supposed to do is return
the tags, one by one.
Should we handle the case in which the
comment ("<!--" or "-->") is in more than
one line?
Answer in handout:
This example is given in discussing
discardComment:
"what + \n this is the second line -- \n here
it the third line \n -->stuff following"
8
Questions about A3 that we get
Let's say that there is <<< asdvc >>, then
how do we interpret this??
Answer in handout:
There is no specific answer on the handout.
However, we don’t expect you to detect all
sorts of error in an html page. That is not the
purpose of the handout. A tag is simply <
followed by some chars followed by >. Using
this, the string <<< asdvc>> has ONE tag:
<<< asdvc>
In looking for tags, find the first <; the tag ends
with the first > after that.
9
Nested Classes
public class X {
public static final int Y= 2;
private int x;
private static class SC {
private int p;
private static int q;
public void m()
{ p= Y; q= p; }
}
}
Y 2
x ?
X
In method m, can
reference, p, q, Y, but
not field x.
q ?
b1
b2
Reason for using
nested class. Get it
out of the way;
make it private so
others can’t refer to
it directly.
SC
p ?
m() {p= Y; q= p;}
SC’s file drawer
x’s file drawer
inside-out rule: method can reference
things declared in surrounding constructs
10
Example of static class in Hashset
public class HashSet {
private static final int TABLE_SIZE= 101;
/** An instance is an entry in the hash table */
private static class HashEntry {
public Object element; // the element
public boolean isInSet;
/** Constructor: an entry that is in set */
public HashEntry(Object e)
{ this(e, true); }
/** Constructor: an entry that is in set iff b */
public HashEntry(Object e, boolean b) {
element= e;
isInSet= b;
}
}
}
HashEntry doesn’t have to refer to
…
fields of HashSet, so make it static.
Software Engineering principle:
Hide things that need no be seen.
11
Inner classes
An inner class: non-static class I that is
defined inside another class O.
Reason for making a class an inner class:
(1) You don’t want the reader to have to deal
with it; user should not see it.
(2) Reduce the number of files one has to deal
with.
(3) Methods in class I have to refer to fields of
class O in which it is placed (so it can’t be
a nested class (i.e. a static class). Placing
class I within class O simplifies referring
to these fields.
12
Example of Inner Class
public class HashSet {
private HashEntry[] b;
private int size;
private class HashSetEnum
implements Iterator {
private int pos= -1; // items in …
private int visited= 0; //…
public boolean hasNext()
{ return visited != size(); }
public Object next() {
pos= pos+1;
while (pos != b.length && … )
{ pos= pos+1; }
…
}
}
}
13
File drawer for HashSet
It contains a file drawer for HashSetEnum
a1
HashSet
b a2
size 256
File drawer for HashSetEnum
File drawer for HashSet
14
File drawer for HashSet
An instance of HashSetEnum is created
a1
HashSet
b a2
a3
size 256
pos 20
HashSetEnum
visited 3
hasNext() next()
File drawer for HashSetEnum
File drawer for HashSet
15
File drawer for HashSet
Second instance of HashSetEnum is created
a1
HashSet
b a2
a3
size 256
pos 20
HashSetEnum
visited 3
hasNext() next()
a4
pos 50
HashSetEnum
visited 6
hasNext() next()
File drawer for HashSetEnum
File drawer for HashSet
16
File drawer for HashSet
Second instance of HashSet is created
a1
b a2
HashSet
a3
HashSetEnum
size 256
a3
HashSetEnum
a6
b a7
HashSet
size 64
File drawer for HashSet
17
File drawer for HashSet
HashSetEnum is created for second HashSet
a1
b a2
HashSet
a3
HashSetEnum
size 256
a3
HashSetEnum
a6
b a7
size 64
HashSet
a3
HashSetEnum
File drawer for HashSet
18
Referencing nested/inner classes from outside
public class Outer {
public Outer() {
System.out.println("Outer constructor");
}
public class Inner {
public Inner() {
System.out.println("Inner constructor");
}
}
}
public class TestClass {
public static void main(String[] args) {
Outer oc= new Outer();
Outer.Inner ic= oc.new Inner();
}
}
19
Functors (function objects)
Interface Comparable doesn’t fit all situations.
Several ways to sort an array of integers -ascending order, descending order, in order of
distance from 0 (e.g. 0,1,-1, 2, -2, 3, -4, …), etc.
Want to use the same sort method to sort the
array in any order.
Solution: pass a comparison function to method
sort:
// Sort array b using sort method f
public static void sort(int[] b, function f) {
… if f(b[i],b[j]) ...
}
illegal in Java!
public static void main(String[] pars) {
int[] x= new int[50]; …
sort(x, greaterequal);
}
// = “x >= y”
public static boolean greaterequal(int x, int y)
{return x >= y;}
20
Functors (function objects)
A function cannot be an argument, but an
instance of a class that is guaranteed to contain a
function can!
// A functor with boolean function compare(x,y)
public interface CompareInterface {
/** = x <= y */
boolean compare(Object x, Object y);
}
An instance of CompareInterface is a
functor: an instance with exactly one
function defined it it.
// Sort array b using functor c
public static void sort(int[] b,
CompareInterface c) {
…
if c.compare(b[i],b[j]) ...
}
parameter c is guaranteed
to contain function compare
21
Functor: An instance of a class with one
function defined in it
// A functor with boolean function compare(x,y)
public interface CompareInterface {
/** = x <= y */
boolean compare(Object x, Object y);
}
// Sort array b using functor c
public static void sort(int[] b,
CompareInterface c) {
…
if c.compare(b[i],b[j]) ...
}
22