1 / 22

Nested and Inner classes

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. 8-queens solution.

iolani
Download Presentation

Nested and Inner classes

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  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. 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. */ publicstaticvoid 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. 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" */ publicstaticboolean 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) returnfalse; } returntrue; } col cm-i. col cm. col cm+i. row m-i row m

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

  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 "<!--" and end with "-->": <!-- this text is ignored --> Everything before the closing "-->" is ignored, even if the comment contains ">". 

  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: <a width=5height=6> <a width=5 height=6>

  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 ("<!--" 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"

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

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

  11. Example of static class in Hashset publicclass HashSet { privatestaticfinalint TABLE_SIZE= 101; /** An instance is an entry in the hash table */ privatestaticclass 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. Inner classes An inner class: non-static class I that is defined inside another class O. Reason for making a class an inner class: You don’t want the reader to have to deal with it; user should not see it. Reduce the number of files one has to deal with. 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. Example of Inner Class publicclass HashSet { private HashEntry[] b; privateint size; privateclass HashSetEnum implements Iterator { privateint pos= -1; // items in … privateint visited= 0; //… publicboolean hasNext() { return visited != size(); } public Object next() { pos= pos+1; while (pos != b.length && … ) { pos= pos+1; } … } } }

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

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

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

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

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

  19. Referencing nested/inner classes from outside publicclass Outer { public Outer() { System.out.println("Outer constructor"); } publicclass Inner { public Inner() { System.out.println("Inner constructor"); } } } publicclass TestClass { publicstaticvoid main(String[] args) { Outer oc= new Outer(); Outer.Inner ic= oc.new Inner(); } }

  20. illegal in Java! 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= newint[50]; … sort(x, greaterequal); } // = “x >= y” public static boolean greaterequal(int x, int y) {return x >= y;}

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

More Related