- Forward


Empty Classes
An Introduction with Examples in Java


Prof. David Bernstein
James Madison University

Computer Science Department
bernstdh@jmu.edu

Print

Motivation
Back SMYC Forward
  • Interfaces are Very Powerful:
    • They give classes the opportunity to "leverage" polymorphism
  • Realizing Interfaces Can Be Cumbersome:
    • Some interfaces have many methods and it can be cumbersome to implement them all
A Workaround
Back SMYC Forward
  • The Idea:
    • Always create a class that contains empty implementations of all of the methods and, as needed, create a specialization that overrides some or all of the empty method
  • The Limitation:
    • A derived class can only use this workaround with one interface (since Java uses single inheritance)
An Example
Back SMYC Forward
  • The Interface:
    • The MouseListener interface has five methods: mouseClicked(), mouseEntered(), mouseExited(), mousePressed(), and mouseReleased()
  • A Common Situation:
    • Classes only "care about" mouseClicked()
A Design Issue
Back SMYC Forward
  • A Seemingly Obvious Decision:
    • Make the empty class abstract to prevent people from misusing it
  • The Shortcoming of this Decision:
    • It prevents you from overriding the empty methods in an anonymous class that is used at construction-time
Empty Classes in Java
Back SMYC Forward
  • An Observation:
    • Java has many such classes
  • A Terminological Issue:
    • Java calls them "adapters" but this is confusing because they are not related to the Adapter Pattern (the two were being developed at around the same time and just happened to use the same term)
  • Some Examples:
    • DragSourceAdapter , DropTargetAdapter , KeyAdapter , MouseAdapter , and MouseMotionAdapter
An Example
Back SMYC Forward

Using an Anonymous Class

// Add a MouseListener that will respond to mouseClicked messages panel.addMouseListener( new MouseAdapter() // An anonymous inner class that overrides mousePressed() in MouseAdapter { public void mouseClicked(MouseEvent e) { System.out.println("I've been clicked!"); } } );
There's Always More to Learn
Back -