Presentation is loading. Please wait.

Presentation is loading. Please wait.

1 Nested and Inner classes Reading for these lectures: Weiss, Section 15.1 (Iterators and nested classes), Section 15.2 (Iterators and inner classes).

Similar presentations


Presentation on theme: "1 Nested and Inner classes Reading for these lectures: Weiss, Section 15.1 (Iterators and nested classes), Section 15.2 (Iterators and inner classes)."— Presentation transcript:

1 1 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.

2 2 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); }

3 3 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; } return true; } row m-i row m col cm-i. col cm. col cm+i.

4 4 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. 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; } } Reasons for using nested class. Get it out of the way; perhaps make it private so others can’t refer to it directly. In method m, can reference, p, q, Y, but not x. A class that is not defined inside another can’t be static

5 5 Questions about A3 that we get Should we include 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. …/ 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)

6 6 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 new- line characters. … Since attributes are in tags, tags can span sev- eral lines. As the examples in the table show Can a comment include a tag? Answer on handout: Comments begin with " ": Everything before the closing "-->" is ignored, even if the comment contains ">".

7 7 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:

8 8 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 (" ") 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"

9 9 Questions about A3 that we get Let's say that there is >, 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. Using this, the string > has ONE tag: In looking for tags, find the first after that.

10 10 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; } } In method m, can reference, p, q, Y, but not field x. Reason for using nested class. Get it out of the way; make it private so others can’t refer to it directly. x’s file drawer Y 2 SC’s file drawer ? q b1 SC ? p m() { p= Y; q= p;} b2 X ? x inside-out rule: method can reference things declared in surrounding constructs

11 11 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.

12 12 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.

13 13 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; } … }

14 14 File drawer for HashSet a1 File drawer for HashSetEnum b a2 size 256 HashSet It contains a file drawer for HashSetEnum

15 15 File drawer for HashSet a1 File drawer for HashSetEnum b a2 size 256 a3 pos 20 3 visited hasNext() next() HashSetEnum HashSet An instance of HashSetEnum is created

16 16 File drawer for HashSet a1 File drawer for HashSetEnum b a2 size 256 a3 pos 20 3 visited hasNext() next() HashSetEnum HashSet a4 pos 50 6 visited hasNext() next() HashSetEnum Second instance of HashSetEnum is created

17 17 File drawer for HashSet a1 b a2 size 256 a3 HashSetEnum HashSet Second instance of HashSet is created a3 HashSetEnum a6 b a7 size 64 HashSet

18 18 File drawer for HashSet a1 b a2 size 256 a3 HashSetEnum HashSet HashSetEnum is created for second HashSet a3 HashSetEnum a6 b a7 size 64 HashSet a3 HashSetEnum

19 19 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(); }

20 20 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])... } 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;} illegal in Java!

21 21 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); } // Sort array b using functor c public static void sort(int[] b, CompareInterface c) { … if c.compare(b[i],b[j])... } An instance of CompareInterface is a functor: an instance with exactly one function defined it it. parameter c is guaranteed to contain function compare

22 22 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])... }


Download ppt "1 Nested and Inner classes Reading for these lectures: Weiss, Section 15.1 (Iterators and nested classes), Section 15.2 (Iterators and inner classes)."

Similar presentations


Ads by Google