Title: MIT AITI 2004 Lecture Supplement
1MIT AITI 2004 Lecture Supplement
2Calc Design Problems
- Calc has a separate small class for every
listener Lots of classes! - Every listener for Calc has package access so
other classes inside the same package could
potentially use them - Couldn't we put the listener classes inside Calc
somehow and make them private?
3Inner Classes
- Inner classes are classes we put inside other
classes. - They are declared inside the braces of the class
just like fields and methods
class MyClass // fields here // methods
here // inner classes here
4Inner Class Syntax
- Syntax for declaring an inner class is the same
as the syntax for a regular class, except inner
classes can be static and private - Examples
class MyClass private static class
MyInnerClass1 . . . public class
MyInnerClass2 . . . static class
MyInnerClass3 . . .
5Inner Class Accessibility
- The inner class has access to all the private
members of the enclosing class - But the enclosing class does not have access to
the private members of the inner class - This makes sense when you think of the definition
of private accessible only within the class.
6Static vs Non-Static Inner Class
- Non-static inner classes have access to all the
members of the enclosing class - Static inner classes have access to only the
static members of the enclosing class - If an inner class doesn't need access to a
non-static member of the enclosing class, you
should make it static.
7Non-Static Inner Class Example
public class Calc private class
CalcListener implements
ActionListener public void
actionPerformed(ActionEvent e) // place
code from calculatePressed here
- Now you can delete the calculatePressed method
and the old CalcListener class file. - Why must this class be non-static?
8Static Inner Class Example
public class Calc private static class
Quitter implements
ActionListener public void
actionPerformed(ActionEvent e)
System.exit(0)
- Create an instance of Quitter and add it as a
listener to the quit button - Why can this class be static?
9Inner Class Challenge
- Make ClickPrinter an inner class and delete the
separate ClickPrinter class file - Should this inner class be static or non-static?
- Now your whole Calc program is located within a
single file Calc.java