Algorithms and OOD (CSC 207 2014S) : EBoards

CSC207.01 2014S, Class 22: Detour: Anonymous Inner Classes


Overview

Preliminaries

Upcoming Work.

Admin

Questions

Anonymous inner classes - the concept

Sometimes you want functions and it's not worth your time/effort to name them.

(set! grades (map (l-s + .25) grades))

vs.

(define fixgrade
  (lambda (x) (+ .25 x)))
(set! grades (map fixgrade grades))

First is shorter

Giving something a name takes mental energy and pollutes the namespace.

In Java, anonymous things are also useful

In Java, anonynous is particularly useful because we have to write a lot when we declare a new class.

Java has anonymous classes

We use them to provide the functions that we need above.

Anonymous inner classes - the implementation

new Interface() { Method implementations }

E.g.,

public interface Checker { public boolean okay(Object o); } // interface Checker

public class Sam { public static Object search(Object[] values, Checker check) { for (v : values) if (check.okay(v)) return v; } // search(Object[], Checker) } // class Sam

Sam.search(students, new Checker() { public boolean okay(Object o) { return o.toString.contains("k"); } // okay } // Checker );

public class SamR { public static Object searchByString(Object[] values, final String str) { Sam.search(students, new Checker() { public boolean okay(Object o) { return o.toString.contains(str); } // okay } // Checker ); } } // class SamR

Some subtleties

Copyright (c) 2013-14 Samuel A. Rebelsky.

Creative Commons License

This work is licensed under a Creative Commons Attribution 3.0 Unported License. To view a copy of this license, visit http://creativecommons.org/licenses/by/3.0/ or send a letter to Creative Commons, 543 Howard Street, 5th Floor, San Francisco, California, 94105, USA.