- Forward


Local Classes
An Introduction with Examples in Java


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu

Print

Motivation
Back SMYC Forward
  • Recall:
    • Static nested class and inner classes allows a class that is tightly coupled to another class to be defined within it
  • A Related Situation:
    • You want to define a class within a block
Access
Back SMYC Forward
  • Members in the Enclosing Class:
    • The local class can access all members
  • Access to Local Variables:
    • The local class can access all local variables that are declared to be final or (since Java v8) are effectively final
Common Uses
Back SMYC Forward
  • The Idea:
    • One encapsulation is good for most purposes but for some purposes an alternative encapsulation is preferred (and it would be confusing to expose both)
  • Examples:
    • A rectangle can be encapsulated as a corner, width and height; or as two opposing corners
    • An ellipse can be encapsulated as a point and two radii; or as its bounding rectangle
    • A phone number can be enacpsulated as a string; or as an area code, exchange, and extension
An Example
Back SMYC Forward
javaexamples/nested/Rectangle.java
 
An Example with an Interface
Back SMYC Forward
javaexamples/nested/ComparatorExample.java (Fragment: local)
 
There's Always More to Learn
Back -