Some intuition on Java class hierarchies
Previous    Next    Home     Java Source    Package

// This sequence is intended to aid in understanding a few things about Java:
//  1. A component such as JButton can be used inside another component
//     such as JFrame regardless of whether JButton subclasses JFrame or
//     vice versa or neither subclasses the other
//  2. When a class implements an interface, say I, objects of that class
//     also are of type I.  This allows a class such as JButton, which 
//     provides a service (doing something when a button is pressed), to
//     listen to an object of any class (which is also of type I) and to
//     provide a callback to that object.
//  3. In Java we can inherit from at most one super class but we can
//     achieve the same power as in multiple inheritance by creating
//     an object of the class that will provide the needed service and
//     run methods of that class from that object.
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.applet.*;

// Alternatively, we can create a special instance of the class MouseAdapter
// which also provides the service of listening to mouse events.  Now objects
// of type A21 are not of type MouseListener, but that is OK since we make use
// of the special MouseAdapter object to handle the listening.  This means
// we cannot use butt.addMouseListener(this) because this does not refer to
// a MouseListener object.  But we can use butt.addMouseListener(ma) because
// ma is of type MouseAdapter, which implements MouseListener and is there
// of the needed type.  Notice that the callback never gets back to the 
// A21 object w - instead it is directed to the ma object.  The object w
// never needs to access the ma object because the ma object takes care of
// all the mouse event servicing that needs to be done.
class A21 extends JFrame {
   JButton butt = new JButton("Yikes");
   JTextArea text = new JTextArea();

   MouseAdapter ma = new MouseAdapter() { 
      public void mousePressed(MouseEvent evt) {
         text.append("Mouse button pressed\n");
      }

      public void mouseReleased(MouseEvent evt) {
         text.append("Mouse button released\n");
      }
   };

   public A21 () {
      setLayout(new BorderLayout());
      add("North",butt);
      add("Center",text);
      butt.addMouseListener(ma);
      setSize(300,300);
      setVisible(true);
   }
}

public class A2 extends Applet {
   public void init () {
      A21 w = new A21();
      w.setSize(300,300);
      w.setVisible(true);
   }
}