MIT AITI 2004 Lecture Supplement - PowerPoint PPT Presentation

1 / 9
About This Presentation
Title:

MIT AITI 2004 Lecture Supplement

Description:

{ private static class Quitter. implements ActionListener ... Create an instance of Quitter and add it as a listener to the quit button ... – PowerPoint PPT presentation

Number of Views:65
Avg rating:3.0/5.0
Slides: 10
Provided by: gregory65
Category:

less

Transcript and Presenter's Notes

Title: MIT AITI 2004 Lecture Supplement


1
MIT AITI 2004 Lecture Supplement
  • Inner Classes

2
Calc 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?

3
Inner 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
4
Inner 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 . . .
5
Inner 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.

6
Static 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.

7
Non-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?

8
Static 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?

9
Inner 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
Write a Comment
User Comments (0)
About PowerShow.com