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

Slides:



Advertisements
Similar presentations
Arrays.
Advertisements

Static Methods Static methods are those methods that are not called on objects. In other words, they don’t have an implicit parameter. Random number generation.
Variable types We have already encountered the idea of a variable type. It is also possible to think about variables in terms of their kind, namely: 1)
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
For use of IST410 Students only Arrays-1 Arrays. For use of IST410 Students only Arrays-2 Objectives l Declaring arrays l Instantiating arrays l Using.
Road Map Introduction to object oriented programming. Classes
1 CS100J 13 March 2006 Arrays. Reading: Secs 8.1, 8.2, 8.3. Listen to the following lectures on loops on your Plive CD. They are only 2-3 minutes long,
Access to Names Namespaces, Scopes, Access privileges.
Searching. 2 Searching an array of integers If an array is not sorted, there is no better algorithm than linear search for finding an element in it static.
1 Interfaces and related issues Reading for these lectures: Weiss, Section 4.4 (The interface), p no multiple inheritance with classes public class.
1 CS100J 14 March 2006 Arrays. Reading: Secs 8.1, 8.2, 8.3. Listen to the following lectures on loops on your Plive CD. They are only 2-3 minutes long,
Computer Science 1620 Multi-Dimensional Arrays. we used arrays to store a set of data of the same type e.g. store the assignment grades for a particular.
1 What’s a class People are confused with nested classes and anonymous classes. Experiments in a recitation last week revealed that the problems were probably.
CS102--Object Oriented Programming Lecture 6: – The Arrays class – Multi-dimensional arrays Copyright © 2008 Xiaoyan Li.
Terms and Rules Professor Evan Korth New York University (All rights reserved)
28-Jun-15 Access to Names Namespaces, Scopes, Access privileges.
Java Programming: From Problem Analysis to Program Design, 4e Chapter 7 User-Defined Methods.
1 Implementing a queue in an array Hashing We show a neat idea that allows a queue to be stored in an array but takes constant time for both adding and.
1 Inner classes Reading for these lectures: Weiss, Section 15.1 (Iterators and nested classes), Section 15.2 (Iterators and inner classes). A nested class.
CS/ENGRD 2110 SPRING 2013 Lecture 2: Introduction to Java 1.
Options for User Input Options for getting information from the user –Write event-driven code Con: requires a significant amount of new code to set-up.
CS2110 Recitation 07. Interfaces Iterator and Iterable. Nested, Inner, and static classes We work often with a class C (say) that implements a bag: unordered.
Java Unit 9: Arrays Declaring and Processing Arrays.
Week 4-5 Java Programming. Loops What is a loop? Loop is code that repeats itself a certain number of times There are two types of loops: For loop Used.
(c) University of Washingtonhashing-1 CSC 143 Java Hashing Set Implementation via Hashing.
1 Web Based Programming Section 6 James King 12 August 2003.
1 Lecture 07 Interfaces and related issues Reading for these lectures: Weiss, Section 4.4 (The interface), p ProgramLive, Section 12.1 In User Interface.
Topic 3 The Stack ADT.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Summary and Exam COMP 102.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Comp 248 Introduction to Programming Chapter 6 Arrays Part B Dr. Aiman Hanna Department of Computer Science & Software Engineering Concordia University,
CSCI-383 Object-Oriented Programming & Design Lecture 13.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
CIT 590 Intro to Programming First lecture on Java.
CS 206 Introduction to Computer Science II 09 / 10 / 2009 Instructor: Michael Eckmann.
DATA STRUCTURES LAB 1 TA: Nouf Al-harbi
RIT Computer Science Dept. Goals l Inheritance l Modifiers: private, public, protected l Polymorphism.
CSC 205 Programming II Lecture 18 The Eight Queens Problem.
Java 5 Part 1 CSE301 University of Sunderland Harry Erwin, PhD.
Questions? Suggestions?. References References Revisited What happens when we say: int x; double y; char c; ???
Two-Dimensional Arrays That’s 2-D Arrays Girls & Boys! One-Dimensional Arrays on Steroids!
CSE 143 Lecture 24 Advanced collection classes (ADTs; abstract classes; inner classes; generics; iterators) read 11.1, 9.6, , slides.
1 Exception handling in Java Reading for this lecture: Weiss, Section 2.5 (exception handling), p. 47. ProgramLive, chapter 10. I need to know whether.
This recitation 1 An interesting point about A3: Using previous methods to avoid work in programming and debugging. How much time did you spend writing.
Exceptions Chapter 16 This chapter explains: What as exception is Why they are useful Java exception facilities.
COP3502 Programming Fundamentals for CIS Majors 1 Instructor: Parisa Rashidi.
CMSC 202 Arrays 2 nd Lecture. Aug 6, Array Parameters Both array indexed variables and entire arrays can be used as arguments to methods –An indexed.
Programming and Problem Solving With Java Copyright 1999, James M. Slack Exceptions Handling Exceptions with try and catch The finally-block The throws.
CS305j Introduction to Computing Classes II 1 Topic 24 Classes Part II "Object-oriented programming as it emerged in Simula 67 allows software structure.
Interfaces and Inner Classes
Programmeren 1 6 september 2010 HOORCOLLEGE 2: INTERACTIE EN CONDITIES PROGRAMMEREN 1 6 SEPTEMBER 2009 Software Systems - Programming - Week.
Iterators ITI 1121 N. El Kadri. Motivation Given a (singly) linked-list implementation of the interface List, defined as follows, public interface List.
Generic Programming and Inner classes ge·ner·ic 1a : relating or applied to or descriptive of all members of a genus, species, class, or group : common.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Summary and Exam COMP 102.
Topic 8Classes, Objects and Methods 1 Topic 8 l Class and Method Definitions l Information Hiding and Encapsulation l Objects and Reference Classes, Objects,
Sets and Maps Part of the Collections Framework. 2 The Set interface A Set is unordered and has no duplicates Operations are exactly those for Collection.
Iteration Abstraction SWE Software Construction Fall 2009.
Java: Variables and Methods By Joshua Li Created for the allAboutJavaClasses wikispace.
CS/ENGRD 2110 FALL 2013 Lecture 3: Fields, getters and setters, constructors, testing 1.
Chapter 9: Continuing Classes By Matt Hirsch. Table Of Contents 1.Static Fields and Methods 2.Inheritance I. Recycle Code with Inheritance II. Overriding.
ENCAPSULATION. WHY ENCAPSULATE? So far, the objects we have designed have all of their methods and variables visible to any part of the program that has.
Lecture 5: Some more Java!
Week 6 Discussion Word Cloud.
Subroutines Idea: useful code can be saved and re-used, with different data values Example: Our function to find the largest element of an array might.
Functions BIS1523 – Lecture 17.
CSE 1030: Implementing Non-Static Features
Namespaces, Scopes, Access privileges
Java Programming Language
Arrays.
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. */ 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 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 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 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 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 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 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 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 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 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 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 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 File drawer for HashSet a1 File drawer for HashSetEnum b a2 size 256 HashSet It contains a file drawer for HashSetEnum

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