/** Driver class for inner class example, from recitation 5 Jan 2001 */ class Outer { private int sum; /* note: having this variable out here with class scope is not a particularly good design decision. */ /** Implementation of a file summer with a named inner class */ int sumFileV1 (String fileName) { sum = 0; ProcessFile (fileName, new addLine ()); return sum; } // end sumFileV1 /** Implementation of a file summer with an anonymous inner class */ int sumFileV2 (String fileName) { sum = 0; ProcessFile (fileName, new LineProcessor() { public void doIt (String line) { sum += Integer.parseInt(line); } } ); return sum; } // end sumFileV2 /** Implementation of a file summer that doesn't use an outer class variable */ int sumFileV3 (String fileName) { LPReturningInt lp; // We need to instantiate this into a variable so we // can call it at the end to return its answer lp = new LPReturningInt () { private int mySum = 0; public void doIt (String line) { mySum += Integer.parseInt(line); } public int getAnswer () { return mySum; } }; ProcessFile (fileName, lp); return lp.getAnswer(); } // end sumFileV3 /** Named inner class to add line's value to outer class property */ private class addLine implements LineProcessor { public void doIt (String line) { sum += Integer.parseInt(line); // .IntegerValue(); /* The example in class erroneously tried to call IntegerValue here. But it turns out that parseInt returns an int, not an Integer. */ } } /** Driver method for callbacks */ void ProcessFile (String fileName, LineProcessor lp) { String line; while ((line = MagicallyGetLine (fileName)) != null) lp.doIt (line); } /** Dummy so we can compile */ String MagicallyGetLine (String fileName) { return null; } } interface LineProcessor { public void doIt (String line); } interface LPReturningInt extends LineProcessor { public int getAnswer (); }